How to reverse a string in C#?

Member

by craig , in category: Other , 2 years ago

How to reverse a string in C#?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by ubaldo.rau , 2 years ago

@craig you can convert string to an array of chars and then reverse array and then implode chars into string in C#, implementation:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
using System;

namespace HelloWorld
{
	public class Program
	{
		public static void Main(string[] args)
		{
		   string str = "test string";
		   // Convert to array of chars
		   char[] arr = str.ToCharArray();
		   // reverse array
           Array.Reverse(arr);
           str = new string(arr);
		   // Output: gnirts tset
           System.Console.WriteLine(str);
		}
	}
}
by mazie_pollich , 10 months ago

@craig 

There are several ways to reverse a string in C#, but here are three common methods:

  1. Using a for loop:
1
2
3
4
5
6
7
8
9
string originalString = "Hello World!";
string reversedString = "";

for (int i = originalString.Length - 1; i >= 0; i--)
{
    reversedString += originalString[i];
}

Console.WriteLine(reversedString);  // Output: !dlroW olleH


  1. Using the Array.Reverse method:
1
2
3
4
5
6
string originalString = "Hello World!";
char[] charArray = originalString.ToCharArray();
Array.Reverse(charArray);
string reversedString = new string(charArray);

Console.WriteLine(reversedString);  // Output: !dlroW olleH


  1. Using the StringBuilder class:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
string originalString = "Hello World!";
StringBuilder sb = new StringBuilder(originalString);

for (int i = 0; i < originalString.Length / 2; i++)
{
    char temp = sb[i];
    sb[i] = sb[originalString.Length - i - 1];
    sb[originalString.Length - i - 1] = temp;
}

string reversedString = sb.ToString();

Console.WriteLine(reversedString);  // Output: !dlroW olleH