- Home /
How can I detecting whether certain characters appear in any strings in my array of strings?
the problem is that it doesn't find the char "h" in one of the randomly chosen words (hel,hello1,hello2) which DO contain the char "h", In contrast to that it does finds "l" char, in word hel it finds once, in hello1 or hello2 it finds twice.. so what's the problem?
if(GUI.Button(Rect (100,265,50,50), "H",Circle)){
for (var i : int = 0; i < randomWord.Length; i++) { search = "h"; found = randomWord.IndexOf(search, i); if (found>0) { totalFinds++; i = found;
// search = ""; }
}
print ("Found = "+totalFinds); }
Answer by duck · May 14, 2010 at 09:46 AM
You problem seems to be that IndexOf returns the position of the character found in the string, and the position of characters is zero-based. That is, if the character is found as the first character of the string, the result will be zero.
Your script checks whether the result is larger than zero, so it won't detect any characters at the start of the string.
The MSDN docs for string.IndexOf state that the function returns -1 if no chars are found, so to fix, simply change your code from:
if (found>0)
to
if (found>=0)
EDIT: Although, on closer inspection, it seems that you don't need to be using IndexOf at all, because you're already stepping through the chars in your word already. Something like this should suffice:
var search = "h";
var totalFinds = 0;
for (var i : int = 0; i < randomWord.Length; i++)
{
if (randomWord[i] == search)
{
totalFinds++;
}
}
print ("Found = "+totalFinds);
}