10

Example:

string str = "I am going to reverse myself.";
string strrev = "I ma gniog ot esrever .flesym"; //An easy way to achieve this

As I think I have to iterate through each word and then each letter of every word.

What I have done works fine. But I need easy/short way.

C# CODE:

  string str = "I am going to reverse myself.";
  string strrev = "";

  foreach (var word in str.Split(' '))
  {
     string temp = "";
     foreach (var ch in word.ToCharArray())
     {
         temp = ch + temp;
     }
     strrev = strrev + temp + "";
  }
  Console.WriteLine(strrev);  //I ma gniog ot esrever .flesym
Javed Akram
  • 15,024
  • 26
  • 81
  • 118

9 Answers9

17

Well, here's a LINQ solution:

var reversedWords = string.Join(" ",
      str.Split(' ')
         .Select(x => new String(x.Reverse().ToArray())));

If you're using .NET 3.5, you'll need to convert the reversed sequence to an array too:

var reversedWords = string.Join(" ",
      str.Split(' ')
         .Select(x => new String(x.Reverse().ToArray()))
         .ToArray());

In other words:

  • Split on spaces
  • For each word, create a new word by treating the input as a sequence of characters, reverse that sequence, turn the result into an array, and then call the string(char[]) constructor
  • Depending on framework version, call ToArray() on the string sequence, as .NET 4 has more overloads available
  • Call string.Join on the result to put the reversed words back together again.

Note that this way of reversing a string is somewhat cumbersome. It's easy to create an extension method to do it:

// Don't just call it Reverse as otherwise it conflicts with the LINQ version.
public static string ReverseText(this string text)
{
    char[] chars = text.ToCharArray();
    Array.Reverse(chars);
    return new string(chars);
}

Note that this is still "wrong" in various ways - it doesn't cope with combining characters, surrogate pairs etc. It simply reverses the sequence of UTF-16 code units within the original string. Fine for playing around, but you need to understand why it's not a good idea to use it for real data.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Is collision with `Enumerable.Reverse` really a problem/undesirable? Your function fulfills the contract for `Enumerable.Reverse` too, apart from deferred execution. And since `string` is immutable and already evaluated the the deferred execution is unobservable. Is it because a version of this function which deals with the unicode problems wouldn't fulfill the contract of `Enumerable.Reverse`? – CodesInChaos Mar 23 '11 at 09:11
  • @CodeInChaos: No, it's because it's not immediately obvious which version of the code is going to be called. You could end up with odd situations due to having `using` directives at different nesting levels, for example. It's even harder to follow than normal overload resolution :) – Jon Skeet Mar 23 '11 at 09:17
5

To reverse a string I use:

new String( word.Reverse().ToArray() )

The Reverse() function is part of LINQ and works because String implements IEnumerable<char>. Its result is another IEnumerable<char> which now needs to be converted to string. You can do that by calling ToArray() which gives a char[] and then pass that into the constructor of string.

So the complete code becomes:

string s="AB CD";
string reversed = String.Join(" ",
    s.Split(' ')
     .Select(word => new String( word.Reverse().ToArray() ) ));

Note that this code doesn't work well with certain unicode features. It has at least two problems:

  1. Unicode characters outside the basic plane need two chars when UTF-16 encoded. Reversing them breaks the encoding. This is relatively easy to fix since surrogates are a simple range of codepoints which will not change in future unicode versions.
  2. Combining character sequences. For example it's possible to create accented characters by writing the base character and a combining accent behind it. This problem is hard to work around since new combining characters can be added with future unicode versions. Zero-width-joiner will cause similar complications.
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
0

1 - Extension method to reverse a string

  public static string reverseString(this string description) {

        char[] array = description.ToCharArray().Reverse().ToArray();

        return new string(array);
    }

2 - Reversing an array and reversing all string of this array

    public static string reverseText(this string description) {

      string [] reversetext=  description.Split(' ').Select(i => i.ToString().reverseString()).Reverse().ToArray();

      return string.Join(" ", reversetext);
    }
Josh Darnell
  • 11,304
  • 9
  • 38
  • 66
Bamara Coulibaly
  • 729
  • 1
  • 8
  • 7
0

I used XOR for swapping from here http://en.wikipedia.org/wiki/XOR_swap_algorithm

X := X XOR Y
Y := X XOR Y
X := X XOR Y

the C# is:

public  string ReverseWords(string str)
    {
        StringBuilder strrev = new StringBuilder();
        StringBuilder reversedword = new StringBuilder();

        foreach (var word in str.Split(' '))
        {
            char[] singlesentence = word.ToCharArray();
            int j = singlesentence.Length / 2;
            if (j > 0)
            {
                for (int i = singlesentence.Length - 1, c = 0; i == j; c = c + 1, i = i - 1)
                {


                    singlesentence[c] = (char)(singlesentence[c] ^ singlesentence[i]);
                    singlesentence[i] = (char)(singlesentence[c] ^ singlesentence[i]);
                    singlesentence[c] = (char)(singlesentence[c] ^ singlesentence[i]);

                }
            }

            strrev.Append(singlesentence);
            strrev.Append(" ");
        }
        return strrev.ToString();
    }
M.Hefny
  • 2,677
  • 1
  • 26
  • 30
0
//Without Extension Methods Like: Split, ToCharArray, etc..

public string ReverseString(string str="Hai How Are You?"){
    var FullRev="", 
    var wordRev="";
    for(i=0;i<=str.length;i++){
        if(str[i]==" " || i==str.length){
            FullRev=FullRev+" "+wordRev; //FullRev=wordRev+" "+FullRev; 
            wordRev="";
        }else{
            wordRev=str[i]+wordRev;
        }
    }
    return FullRev;
} 
//Result "iaH woH erA ?uoY"
0

you can use linq as

String newStr = new String( str.Reverse().ToArray() );
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103
  • that would replace the inner foreach yes. strrev += " " + word.Reverse(); and then remove the first space of the resultstring. – Vincent Vancalbergh Mar 22 '11 at 12:32
  • String.Reverse will reverse all the string in place and not each word. – mcabral Mar 22 '11 at 12:33
  • @mcabral - Sorry. Edited my answer to make it more explicit. I did not mean to apply reverse on whole string before splitting. – Sachin Shanbhag Mar 22 '11 at 12:38
  • 1
    @mcabral string is immutable. So it can't reverse the string *in place*. @Sachin `String.Reverse()` doesn't exist. Reverse is just an extension method from linq which will return a reversed `IEnumerable`. – CodesInChaos Mar 22 '11 at 12:38
-2
    static void Main(string[] args)
    {
        string str = "Hi how are you";
        char[] char_arr= str.ToCharArray();

        string finalstr = "";           
        string eachwords = "";
        string tempreverseword = "";
        int char_length = char_arr.Length;
        for (int i = 0; i < char_arr.Length; i++)
        {

            if (char_arr[i].ToString() == " " || i == char_length-1)
            {
                if (i == char_length - 1)
                {
                    eachwords += char_arr[i] + "";
                }                   
                char[] revchar_arr = eachwords.ToCharArray();
                for (int j = revchar_arr.Length-1; j >=0; j--)
                {
                    tempreverseword += revchar_arr[j];
                }
                finalstr += tempreverseword+" ";
                tempreverseword = "";                    
                eachwords = "";
            }               
            else
            {
                eachwords += char_arr[i] + "";
            }               
        }
        Console.WriteLine(finalstr);
        Console.ReadKey();

    }
  • While your code looks very cool we also like here to have a sentence or two to introduce it. Like maybe why it is better. I invite you to read this guide : "How I write a good answer" here: https://stackoverflow.com/help/how-to-answer – Guillaume Raymond Jan 10 '20 at 07:40
  • 1
    The code doesn't look "very cool" at all. It uses far too many variables and had terrible performance. – Roland Illig Nov 22 '20 at 08:52
-2
string str = "I am going to reverse myself.";

string[] strArray = str.Split(' ');

string[] strArrayReversed = new string[strArray.Length];

for(int i = 0; i < strArray.Length; i++) 
{

   char[] eachWordLetter = strArray[i].ToCharArray();

   Array.Reverse(eachWordLetter);

   strArrayReversed[i] = new string(eachWordLetter);
}

string newReversedString = String.Join(" ", strArrayReversed);

Console.WriteLine(newReversedString);
Console.ReadLine();
Programer
  • 1
  • 1
-3
public static void ReverseEachWordString(string abc)
        {
            int start_index = 0, end_index = abc.Length - 1;
            int i = 0, j = 0;
            char[] arr = abc.ToCharArray();
            try
            {
                while (start_index < end_index)
                {
                    if (arr[start_index] == ' ')
                    {
                        Console.WriteLine(arr[start_index]);
                        start_index++;
                        i = start_index;
                    }
                    else
                    {
                        if (arr[i] != ' ')
                        {
                            if (i == end_index)
                            {
                                i++;
                                for (j = i - 1; j >= start_index; j--)
                                {
                                    Console.WriteLine(arr[j]);
                                }
                                break;
                            }
                            else
                                i++;
                        }
                        else
                        {
                            for (j = i - 1; j >= start_index; j--)
                            {
                                Console.WriteLine(arr[j]);
                            }
                            i++;
                            start_index = i - 1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }