if (wordUpper[wrdIdx] == wordUpper.Length - 1)
wordUpper[wrdIdx]
returns a
char
representing the character at the specified index.
wordUpper.Length - 1
returns an
int
- a number one less than the length of the string.
In order to compare them, the
char
will be converted to its Unicode code-point.
(Since you're only working with non-accented letters, this is the same as its ASCII[^] value.)
Given the upper-case input string
"MOHIT"
, the numeric value of
wordUpper[wrdIdx]
will be:
77
,
79
,
72
,
73
and
84
. Obviously, none of those values are equal to
wordUpper.Length - 1
, so your loop never terminates. Once
wrdIdx
moves past the end of your string, you get the
IndexOutOfRangeException
when you try to access the next character.
One simple fix would be to use a nested loop:
foreach (char c in wordUpper)
{
for (int i = 0; i < alph.Length; i++)
{
if (c == alph[i])
{
Console.Write(i + " ");
break;
}
}
}