Sunday 3 March 2013

Reverse Words in a Sentence using C#

Reverse Words in a Sentence using C#


               This example explains how to get words by using delimiter ' ' and then reverse each word using String>reverse.

String.Split(new char{' '});//  Splits sentence  into an array words
String.Reverse  Reverses each word ,but returns IEnumerator<char> need to convert it into an Array of char. then re-create String with Array of characters.
 
 static void ReverseWordsInString()
      {
          string original =@"But, in a larger sense, we can not dedicate-- we can
not consecrate-- we can not hallow-- this ground.";
          String[]words=original.Split(new char[] {' '});
          for(int i=0; i < words.Length;i++)
          {
              char[]cWords = words[i].Reverse().ToArray();
              words[i] = new String(cWords);
          }

          foreach (String word in words)
          {
              Console.WriteLine(word);
          }
        original=String.Join(" ", words);
          Console.WriteLine(original);
}


String.Join static function joins by array of words into String. 
Note: We splitted by delimter space ' ', same delimiter used for joining words.

OUTPUT

Input:But, in a larger sense, we can not dedicate-- we can
not consecrate-- we can not hallow-- this ground.

Output:,tuB ni a regral ,esnes ew nac ton --etacided ew ton
nac --etarcesnoc ew nac ton --wollah siht .dnuorg

Tags:  Reverse Words in a Sentence using C#, Reverse word in C# ,String.Reverse ,String.Join,Create new String using char array C#.

No comments:

Post a Comment