Reverse vowels of a string
Reverse only the vowels and leave every other character in place. Two pointers walk in from both ends, skip consonants, and swap whenever both rest on a vowel.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
Reversing the vowels means the first vowel swaps with the last vowel, the second with the second to last, and so on. Two pointers find those pairs directly: l moves right until it sits on a vowel, r moves left until it does too, then they swap and both step inward. Consonants are never touched.
Code
public string ReverseVowels(string s) {
var c = s.ToCharArray();
int l = 0, r = c.Length - 1;
while (l < r) {
if (!IsVowel(c[l])) l++; // not a vowel: it stays put
else if (!IsVowel(c[r])) r--;
else { (c[l], c[r]) = (c[r], c[l]); l++; r--; } // both vowels: swap
}
return new string(c);
}
static bool IsVowel(char ch) => "aeiouAEIOU".IndexOf(ch) >= 0;Tips
- Uppercase vowels count too: "IceCreAm" becomes "AceCreIm".
- A string with an odd number of vowels leaves the middle vowel where it is, because l and r meet on it.
- Strings are immutable in C#, so the work happens on a char array that is turned back into a string at the end.
In the .NET library
string.ToCharArray() copies the characters into a fresh array; new string(char[]) copies them back. For long inputs, string.Create or a Span<char> avoids one of the copies.