Print string in reverse

5

Why can not I print this string in reverse? I know there is a possibility of using a simpler form, 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();
}

Error:

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: 
    
asked by anonymous 19.10.2016 / 15:37

5 answers

8

This is quite simple to solve. Can not start with Length . This property is the size of the array (a string is an array character). Since it starts at 0 it ends at Length - 1 . See:

10 posições       | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Length é 10
Começando em zero | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9  | a última posição é 9

How it works:

using static System.Console;

public class Program {
    public static void Main() {
        string frase = "Diego lima de Aquino";
        for (int i = frase.Length - 1; i >= 0; i--) {
            WriteLine(frase[i]);
        }
    }
}

See running on dotNetFiddle and on CodingGround .

    
19.10.2016 / 15:40
10

The error is in the i statement

int i = frase.Length

Problem

frase.Length returns the number of items within 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, simply decrease 1 in the i statement

for(int i = frase.Length - 1; i>=0; i--)
{
     Console.WriteLine(frase[i]);
}

or

for(int i = frase.Length ; i>=1; i--)
{
     Console.WriteLine(frase[i-1]);
}
    
19.10.2016 / 15:43
9

Because frase.Length has to take 1 , with array started with 0 , frase.Length returns the number of positions, and so frase.Length - 1

for(int i = frase.Length - 1; i>=0; i--)
{
     Console.WriteLine(frase[i]);
}

Example

    
19.10.2016 / 15:41
4

The exception ( IndexOutOfRangeException ) was thrown because you tried to access a position that does not exist in the string.

In the following excerpt:

int i = frase.Length

To resolve the problem, you should start the variable i with the value frase.Length - 1;

Example:

A vector of 5 elements has the following positions: 0, 1, 2, 3, 4 . There is no position 5 (which is the total amount of elements of the data structure).

    
19.10.2016 / 18:52
3

Short and thick:

var reverso = new string(frase.ToCharArray().Reverse().ToArray());
    
19.10.2016 / 20:13