-1

I am trying to get the index of a each char in the 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.

This is the code:

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

Result:

char - index

A - 0

B - 1

C - 2

D - 3

C - 2

E - 5

F - 6

The correct result should be:

char - index

A - 0

B - 1

C - 2

D - 3

C - 4

E - 5

F - 6

Why it's happening?

Thanks

1 Answers1

2

string.IndexOf returns first occurrence of a character, that's why it returns index 2 for c lookup.

MSDN Says,

Reports the zero-based index of the first occurrence of a specified Unicode character or string within this instance. The method returns -1 if the character or string is not found in this instance.

You could convert it to for loop and get index for each character.

for(int i=0;i<textBox1.Text.Length;i++)
{
    MessageBox.Show(textBox1.Text[i] + " - " + i); 
}
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
  • I tried to insert a separator with for loop but did not work. This is the code: for (int i = 0; i < 10; i++) { if (char.IsUpper(textBox1.Text[i])) textBox1.Text = textBox1.Text.Insert(i, " | "); } – Eduardo Angelim Jun 05 '16 at 13:50