Question:
Why can't I print this string
in reverse? I know there is a possibility of using another simpler way, but I want to understand the error.
static void Main(string[] args)
{
string frase = "Diego lima de Aquino";
for(int i = frase.Length; i>=0; i--)
{
Console.WriteLine(frase[i]);
}
Console.ReadKey();
}
Mistake:
System.IndexOutOfRangeException was unhandled HResult=-2146233080 Message=Index was outside the bounds of the array. Source=mscorlib StackTrace: at System.String.get_Chars(Int32 index) at AppNoPrompt_1.Program.Main(String[] args) in C:\Users\Diegolaquino\documents\visual studio 2015\Projects\AppNoPrompt_1\AppNoPrompt_1\Program.cs:line 20 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:
Answer:
The error is in the declaration of the i
int i = frase.Length
Problem
frase.Length
returns the number of items in the array.
frase[i]
, starts at index 0
.
For example 5 items:
frase.Length == 5
frase[0] até frase[4] // frase[5] só existiria se houvesse 6 elementos
To solve this problem just decrease 1 in the declaration of the i
for(int i = frase.Length - 1; i>=0; i--)
{
Console.WriteLine(frase[i]);
}
Where
for(int i = frase.Length ; i>=1; i--)
{
Console.WriteLine(frase[i-1]);
}