对于每个 string.IndexOf(char) 错误?
For each string.IndexOf(char) bug?
var str = "GB29NWBK60161331926819"
foreach (var item in str.ToCharArray())
{
Debug.WriteLine(str.IndexOf(item));
}
给出输出
0
1
2
3
4
5
1
7
8
9
10
8
10
13
13
10
3
2
8
19
10
3
我在期待
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
这是错误还是我的假设不正确?
它为您提供字符串中第一次出现的索引。
查看您的输入字符串,当它命中 1 时,它会为您提供索引 10,当它命中下一个 1 时,它会再次给您。
这是 Documentation 对这个方法的评价:
Reports the zero-based index of the first occurrence of the specified string in this instance.
编辑:ElementAt(int index)
需要一个索引。使用它会在第一个字母 G
处崩溃。它将采用它的 UTF-16 代码,即 71 并越界。
你的期望会因此得到满足:
var str = "GB29NWBK60161331926819";
for (int i = 0; i < str.Length; i++)
{
Debug.WriteLine(i);
}
你的假设是不正确的,因为函数 return 第一次出现在你的字符串中,如果函数匹配 nthing 它将 return -1
您的预期输出仅对于由唯一字符组成的字符串是正确的。
这绝对不是错误,因为您的字符串有重复项。 IndexOf
不会区分 GB
中的 B
和 BWBK
部分中的 B
,给你字符串中字符的第一个索引。
var str = "GB29NWBK60161331926819"
foreach (var item in str.ToCharArray())
{
Debug.WriteLine(str.IndexOf(item));
}
给出输出
0 1 2 3 4 5 1 7 8 9 10 8 10 13 13 10 3 2 8 19 10 3
我在期待
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
这是错误还是我的假设不正确?
它为您提供字符串中第一次出现的索引。
查看您的输入字符串,当它命中 1 时,它会为您提供索引 10,当它命中下一个 1 时,它会再次给您。
这是 Documentation 对这个方法的评价:
Reports the zero-based index of the first occurrence of the specified string in this instance.
编辑:ElementAt(int index)
需要一个索引。使用它会在第一个字母 G
处崩溃。它将采用它的 UTF-16 代码,即 71 并越界。
你的期望会因此得到满足:
var str = "GB29NWBK60161331926819";
for (int i = 0; i < str.Length; i++)
{
Debug.WriteLine(i);
}
你的假设是不正确的,因为函数 return 第一次出现在你的字符串中,如果函数匹配 nthing 它将 return -1
您的预期输出仅对于由唯一字符组成的字符串是正确的。
这绝对不是错误,因为您的字符串有重复项。 IndexOf
不会区分 GB
中的 B
和 BWBK
部分中的 B
,给你字符串中字符的第一个索引。