Print string in reverse

Asked

Viewed 497 times

6

Why can’t I print that string in reverse? I know there is possibility to use 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();
}

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: 

5 answers

11

The error is in the statement of i

int i = frase.Length

Problem

frase.Length returns the amount of items within the array.

frase[i], starts at the 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 i

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]);
}

9

Because, the frase.Length have to take off 1, being the array started with 0, the 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

8


This one is very simple to solve. You can’t start with Length. This property is the size of the array (one string is a array of characters). As it starts at 0 it ends at Length - 1. Behold:

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

That’s 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]);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

4

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

In the following passage:

int i = frase.Length

To solve the problem, you must 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 total amount of data structure elements).

4

Short and thick:

var reverso = new string(frase.ToCharArray().Reverse().ToArray());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.