0

I need to reverse a string using a for loop but I just can't do it. What I'm doing wrong?

class Program
{
    static void Main(string[] args)
    {
        string s;
        string sReverse;

        Console.WriteLine("Say any word please: ");
        s = Console.ReadLine();

        for (int i = 0; i < s.Length; i++)
        {
            s[s.Length - i] = sReversa[i];
        }
    }
}
Sabir Al Fateh
  • 1,743
  • 3
  • 20
  • 27
  • Possible duplicate of [Best way to reverse a string](https://stackoverflow.com/questions/228038/best-way-to-reverse-a-string) – dev-masih Nov 17 '18 at 03:38
  • 2
    There are three errors in the code. You can not use `s[index] = value`, since the `string` is immutable. The first write *(when it would be possible)* would write on the position `[s.Length - 0]`, and this position is out of range, since it s indexed from `0` to `s.Length - 1`. And the last error is, that you are using uninitialised value of `sReversa`. – Julo Nov 17 '18 at 03:42
  • 1
    And a fourth error: if the assignment would have worked, it is the wrong way around (you are attempting to overwrite s) – Hans Kesting Nov 17 '18 at 07:39
  • Even if you fix Julo's and Hans points, there is a fifth error... To demonstrate by example, imagine the string has two characters. First you swap the first character with the last. Then you swap the last with the first, leaving you back where you started. – Richardissimo Nov 17 '18 at 07:40

6 Answers6

1

Strings are immutable. You can't change them character by character.

If you want random access to the characters in a string, convert it to a char array first (using ToCharArray), then convert it back when you're done (String has a constructor that accepts a char array).

string a = "1234";
char[] b = a.ToCharArray();
b[1] = 'X';
a = new string(b);
Console.WriteLine("{0}", a);

Output:

1X34

There are much easier ways to reverse a string (e.g. LINQ would let you do var output = new string(input.Reverse().ToArray());), but if you want to use a for loop and your current approach, this is probably the piece of information you are missing.

John Wu
  • 50,556
  • 8
  • 44
  • 80
1

These will be the minimal changes required in your code:

public static void Main()
    {
        string s;
        string sReverse = string.Empty;   // Initialise (always recommended)

        Console.WriteLine("Say any word please: ");
        s = Console.ReadLine();

        for (int i = s.Length-1; i >=0 ; i--)  // Chnage the order of indexing
        {
            sReverse += s[i];   // makes a new string everytime since strings are immutable.
        }
        Console.WriteLine(sReverse);  // print your new string
    }

As others said this may not be the best approach for very large number of string manipulation / formation. Instead, use StringBuilder.

StringBuilder is suited in situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly.

Below is the snippet on how to use StringBuilder:

using System;
using System.Text;  // Add this for StringBuilder               
public class Program
{
    public static void Main()
    {
        string s;
        StringBuilder sReverse = new StringBuilder();  // Instantiate the object.

        Console.WriteLine("Say any word please: ");
        s = Console.ReadLine();

        for (int i = s.Length-1; i >=0 ; i--)
        {
            sReverse.Append(s[i]);  // Keep Appending to original string.
        }
        Console.WriteLine(sReverse.ToString());  // finally convert to printable string.
    }
}
Koder101
  • 844
  • 15
  • 28
1
string reverse = string.Join("", "some word".Reverse());
JohnyL
  • 6,894
  • 3
  • 22
  • 41
0

You can not use s[s.Length - i] = sReversa[i]; Because Strings are immutable. Instead, you can use sReverse = sReverse + s[Length];

The following code will give you reverse of a string:

 static void Main(string[] args)
    {
        string s;
        string sReverse = "";
        int Length;

        Console.WriteLine("Say any word please: ");
        s = Console.ReadLine();
        Length = s.Length - 1;

        for (int i = Length; i >= 0; i--)
        {
            sReverse = sReverse + s[Length];
            Length--;

        }

        Console.WriteLine("{0}", sReverse);
        Console.ReadLine();
    }

Note: For a large number of iteration, this might be a performance issue.

Sabir Al Fateh
  • 1,743
  • 3
  • 20
  • 27
  • Building a string character by character using the `+` operator [isn't recommended](https://stackoverflow.com/questions/73883/string-vs-stringbuilder). – John Wu Nov 17 '18 at 04:32
  • Yes, For a large number of iteration this might be a performance issue. – Sabir Al Fateh Nov 17 '18 at 04:47
0

The simplest way to make your code work with minimal changes is to use a StringBuilder. Unlike string a StringBuilder is mutable.

Here's the code:

Console.WriteLine("Say any word please: ");
string s = Console.ReadLine();

StringBuilder sb = new StringBuilder(s);

for (int i = 0; i < s.Length; i++)
{
    sb[s.Length - i - 1] = s[i];
}

string r = sb.ToString();
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
0

If you must use a for loop the way you want, you will have to allocate a new char array, initialize it with the string's characters from back to front, then take advantage of the string constructor that takes a char array as input. The code looks as follows:

public static string ReverseWithFor(string s)
{
    if (string.IsNullOrEmpty(s)) return s;
    char[] a = new char[s.Length];
    for (int i = 0; i < s.Length; i++)
        a[s.Length - 1 - i] = s[i];
    return new string(a);
}
dumetrulo
  • 1,993
  • 9
  • 11