Oct 16, 2015

Easy way to reverse each word in a sentence

string str = "I am going to reverse myself.";
 
string strrev = "I ma gniog ot esrever .flesym"; //An easy way to achieve this
 
 
 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);
 
 
Well, here's a LINQ solution:
 
 
var reversedWords = string.Join(" ",
      str.Split(' ')
         .Select(x => new String(x.Reverse().ToArray()))
         .ToArray());
 
  

No comments:

Post a Comment