I have this method that gives me IndexOutOfRangeException, can you guys help me to understand why?
public string FlipString(string inTxt)
{
StringBuilder outTxt = new StringBuilder();
for (int i = inTxt.Length; i > 0; i--)
{
char ch = inTxt[i];
outTxt.Append(ch);
}
Console.WriteLine(outTxt.ToString());
return outTxt.ToString();
}
The method has to be written like this (without the exception)
Arrays in C# are 0-based, not 1-based. You are iterating from
nto 1, but you need to iterate fromn-1to 0:On the other hand, if you just want to reverse the string, there’s a simpler solution using LINQ: