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;
}