Reverse words in a string

Split on whitespace to get the words, reverse their order with two pointers, then rejoin with single spaces.

Time O(n)Space O(n)Code C#
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

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.