Reverse words in a string
Split on whitespace to get the words, reverse their order with two pointers, then rejoin with single spaces.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
Splitting with RemoveEmptyEntries throws away the extra spaces in one step, so leading, trailing and doubled spaces never need special-case code. What is left is an ordinary array reversal with two pointers.
Code
public static string ReverseWords(string s) {
var words = s.Split(' ', StringSplitOptions.RemoveEmptyEntries);
int l = 0, r = words.Length - 1;
while (l < r) { (words[l], words[r]) = (words[r], words[l]); l++; r--; }
return string.Join(' ', words);
}Tips
- string.Join(' ', words) puts exactly one space between words, cleaning up the original spacing.
- The split and the reversal are two separate, simple passes: do not try to do both at once.
In the .NET library
Array.Reverse(words) is the built-in for the middle step; writing it out with l and r makes the pointer movement visible.