I am here with another example on how to reverse the words in a string or sentence?
I have tried with an approach. But I would welcome other approaches as well, please share.
////// Complexity: O(n) + O(n)/2 ~ O(n)
public static string ReverseWordsInString(string str)
{
string reverse = ReverseString(str);
string temp = "";
foreach(string s in reverse.Split(' '))
{
temp += ReverseString(s) + ' ';
}
return temp;
}
private static string ReverseString(string str)
{
char[] chars = str.ToCharArray();
int j = str.Length - 1;
for (int i = 0; i < str.Length / 2; i++)
{
char c = chars[i];
chars[i] = chars[j];
chars[j] = c;
j--;
}
return new string(chars);
}