Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to reverse each word in a sentence

Tags:

string

c#

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
like image 673
Javed Akram Avatar asked Mar 22 '11 12:03

Javed Akram


People also ask

How do you reverse each word in a given string?

We can reverse each word of a string by the help of reverse(), split() and substring() methods. By using reverse() method of StringBuilder class, we can reverse given string. By the help of split("\\s") method, we can get all words in an array.

How do you use reverse in a sentence?

He reversed the position of the two stamps. Another car reversed out of the drive. He reversed and drove away. He reversed his car straight at the policeman.


2 Answers

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.

like image 57
Jon Skeet Avatar answered Oct 19 '22 17:10

Jon Skeet


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 there are just a limited number of characters initiation such a sequence(16 if I remember correctly) and this most likely won't be extended in future unicode versions.
  2. Binding character sequences. For example it's possible to create accented characters by writing the base character and a binding accent behind it. This problem is hard to work around since new combining characters can be added with future unicode versions.
like image 27
CodesInChaos Avatar answered Oct 19 '22 17:10

CodesInChaos