Reverse words in a string, except punctuation

Viewed 2205

Given a string

"hello there, compiler."

how does one reverse every word, except for the punctuation. So after completion this will be printed:

"olleh ereht, relipmoc." 

instead of "olleh ,ereht .relipmoc"

My code (that ignores punctuation):

 static string ReverseString(string s)
 {
     StringBuilder sb = new StringBuilder();
     string[] words = s.Split(' ');

     foreach (var word in words)
     {
         for (int i = word.Length - 1; i >= 0; i--)
         {
             sb.Append(word[i]);
         }

         sb.Append(" ");
     }

     return sb.ToString();
 }
2 Answers
Related