Reverse the ordering of words in a string

I have this string s1 = “My name is X Y Z” and I want to reverse the order of the words so that s1 = “Z Y X is name My”.

I can do it using an additional array. I thought hard but is it possible to do it in place (without using additional data structures) and with the time complexity being O(n)?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReverseStringByWords
{
class Program
{

private static string ReverseAllWords(string str)
{
char[] in_text = str.ToCharArray();
int lindex = 0;
int rindex = in_text.Length - 1;
if (rindex > 1)
{
//reverse complete phrase
in_text = ReverseString(in_text, 0, rindex);

//reverse each word in resultant reversed phrase
for (rindex = 0; rindex <= in_text.Length; rindex++)
{
if (rindex == in_text.Length || in_text[rindex] == ' ')
{
in_text = ReverseString(in_text, lindex, rindex - 1);
lindex = rindex + 1;
}
}
}

return new string(in_text);
}

private static char[] ReverseString(char[] intext, int lindex, int rindex)
{
char tempc;
while (lindex < rindex)
{
tempc = intext[lindex];
intext[lindex++] = intext[rindex];
intext[rindex--] = tempc;
}
return intext;
}

static void Main(string[] args)
{
// Original Sentence: My car is very fast
// Modifies Sentence: fast very is car My
string sample = "My car is very fast";

Console.WriteLine("{0} : {1}", sample, ReverseAllWords(sample));
Console.ReadLine();
}
}
}

Advertisements