gee'K'iran gee'K'iran - 3 months ago 10
C# Question

Reverse words of a sentence without using String.Split in C#

Recently I have been asked in a discussion to write an algorithm to implement reverse of words of a sentence (Not reverse of whole sentence) without using string operations such as Split/Replace/Reverse/Join except ToCharArray and Length. The below is what I could devise in 5min of time. Though the algorithm is working fine, it seems bit ugly style of implementation. Can some body help me by polishing the code.

string ReverseWords(string s)
{
string reverseString = string.Empty;
string word = string.Empty;

var chars = s.ToCharArray();
List<ArrayList> words = new List<ArrayList>();
ArrayList addedChars = new ArrayList();
Char[] reversedChars = new Char[chars.Length];
int i = 1;
foreach (char c in chars)
{
if (c != ' ')
{
addedChars.Add(c);
}
else
{
words.Add(new ArrayList(addedChars));
addedChars.Clear();
}
if (i == s.Length)
{
words.Add(new ArrayList(addedChars));
addedChars.Clear();
}
i++;
}
foreach (ArrayList a in words)
{
for (int counter = a.Count - 1; counter >= 0; counter--)
{
reverseString += a[counter];
}
if(reverseString.Length < s.Length)
reverseString += " ";
}
return reverseString;
}

Answer

This is somewhat simpler:

string inp = "hai how are you?";
StringBuilder strb = new StringBuilder();
List<char> charlist = new List<char>();
for (int c = 0; c < inp.Length; c++ )
{

    if (inp[c] == ' ' || c == inp.Length - 1)
    {
        if (c == inp.Length - 1)
            charlist.Add(inp[c]);
        for (int i = charlist.Count - 1; i >= 0; i--)
            strb.Append(charlist[i]);

        strb.Append(' ');
        charlist = new List<char>();
    }
    else
        charlist.Add(inp[c]);
}
string output = strb.ToString();