简体   繁体   English

在textBox中获取char位置

[英]get char position in textBox

I am trying to get the index of a each char in the text "ABCDCEF" (textBox.text). 我正在尝试获取文本“ ABCDCEF”(textBox.text)中每个字符的索引。 The problem is that the first 'C' index is 2 and the second C index is 4 but the second 'C' index in the result is 2 too. 问题在于,第一个“ C”索引为2,第二个C索引为4,但结果中的第二个“ C”索引也为2。

This is the code: 这是代码:

        foreach (char character in textBox1.Text)
        {
             MessageBox.Show(character + " - " + textBox1.Text.IndexOf(character));
        }

Result: 结果:

char - index 字符索引

A - 0 A-0

B - 1 B-1

C - 2 C-2

D - 3 D-3

C - 2 C-2

E - 5 E-5

F - 6 F-6

The correct result should be: 正确的结果应该是:

char - index 字符索引

A - 0 A-0

B - 1 B-1

C - 2 C-2

D - 3 D-3

C - 4 C-4

E - 5 E-5

F - 6 F-6

Why it's happening? 为什么会这样呢?

Thanks 谢谢

string.IndexOf returns first occurrence of a character, that's why it returns index 2 for c lookup. string.IndexOf返回字符的第一次出现,这就是为什么它返回c查找的索引2的原因。

MSDN Says, MSDN说,

Reports the zero-based index of the first occurrence of a specified Unicode character or string within this instance. 报告此实例中首次出现指定的Unicode字符或字符串的从零开始的索引。 The method returns -1 if the character or string is not found in this instance. 如果在此实例中找不到字符或字符串,则该方法返回-1。

You could convert it to for loop and get index for each character. 您可以将其转换为for循环并获取每个字符的索引。

for(int i=0;i<textBox1.Text.Length;i++)
{
    MessageBox.Show(textBox1.Text[i] + " - " + i); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM