Rectangle 27 0

string How do I reverse text in C ?


Stack<char> charStack = new Stack<char>();
foreach (var c in myString)
{
    charStack.Push(c);
}
StringBuilder sb = new StringBuilder(myString.Length);
while (charStack.Count > 0)
{
    sb.Append(charStack.Pop());
}
string reversed = sb.ToString();
StringBuilder sb = new StringBuilder(myString.Length);
for (int i = myString.Length-1; i >= 0; --i)
{
    sb.Append(myString[i]);
}
string reversed = sb.ToString();
char[] txt = myString.ToArray();
int i = 0;
int j = txt.Length - 1;
while (i < j)
{
    char t = txt[i];
    txt[i] = txt[j];
    txt[j] = t;
    ++i;
    --j;
}
string reversed = new string(txt);

And of course there are many variations to the above.

Another way is to use a stack. Push the individual characters on the stack, then pop them off to populate a StringBuilder:

Another way would be to walk through the string backwards, populating a StringBuilder:

There are several ways you could go about doing this if you don't want to use the built-in facilities. For example, you could create an array, reverse the array (with an explicit loop rather than Array.Reverse), and then create a new string from the array:

Note
Rectangle 27 0

string How do I reverse text in C ?


char[] arr = s.ToCharArray();
Array.Reverse(arr);
var yourString = new string(arr);

You can pass it to Array of char and reverse it :)

Note
Rectangle 27 0

string How do I reverse text in C ?


using System.Linq;

new String(str.Reverse().ToArray());
Note