For loop & Foreach don't complete inside IEnumerator when using IndexOf

Hi,
I’m having a weird problem where a loop won’t complete when I use IndexOf inside the loop.

Here’s my code:

		for (int i = 0; i <= games.Length; i++)
		{
			
			if (games *!= "")*
  •  	{*
    
  •  	iGUIButton button = scrollView2.addElement<iGUIButton>();*
    
  •  	button.type = iGUIButtonType.ButtonBigYellow;*
    

button.label.text = games_.Substring(0,games*.IndexOf(‘?’));
button.variableName = games.Substring(games.IndexOf(‘?’) + 1, games.Length);
button.clickCallback += play; *_

* }*

* }*
Thanks!

EDIT3:
ok i think i found the problem

If we have this string:

Hello World

If we start to extract from the o

Hell"o" (the o)

(Code:

            string hello = "Hello World";

            Console.WriteLine(hello.Substring(hello.IndexOf('o'), hello.Length));

)

and then we set length to hello.Length it except to extract hello.Length chars from startIndex index (hello.indexOf)

i think this can fix the problem, try:

string.Length - indexOf('?')

I update this too in case someone have the same problem and dont see comments

EDIT2:
Since in the comment it look horrible:

Edit

button.variableName = games<em>.Substring(games_.IndexOf('?') + 1, games*.Length);*_</em>

to
button.variableName = games.Substring(games_.IndexOf(‘?’) + 1, games*.Length - 1);
Anyway i think indexOf(‘?’) + 1 can be a problem, are you sure the ‘?’ cant be found at the end of the string? If the ? is at the end it can go out of the string
EDIT: As bunny83 said, the
for (int i = 0; i <= games.Length; i++)
is wrong because “i” will be games.Length and it will cause a index-out-of-bounds exception.
indexOf returns -1 if it failed the search (the string dont have the char)… maybe its the problem?
(I cant comment)*_

As has been pointed out twice, now, your for loop is likely to cause an IndexOutOfRangeException.

In addition, your substring call:

games<em>.Substring(games_.IndexOf('?') + 1, games*.Length);*_</em>

Is likely to cause an ArgumentOutOfRangeException. When calling string.Substring(), you need to make sure that startIndex plus length indicates a valid index in the string.