Wednesday, April 4, 2012

Exercise: Reversing characters per word in a string

I had an exercise to write a function to reverse characters per words in a string, so if I had a string like “I go to school every day” the output would be “I og ot loohcs yreve yad”

I solved this by 2 ways, one using arrays, and the other using stacks

        public static string ReverseWords(string s, char seperator)
{
if (s == null)
return "Arguments error";
Stack<char> wordAccumlator = new Stack<char>(); // stack to hold each word
Stack<char> textAccumlator = new Stack<char>(); //stack to hold the string after reversing words
for (int textIterator = s.Length-1; textIterator >= 0; textIterator--)
{
try
{
// push each character into the stack
wordAccumlator.Push(s[textIterator]);
// if charcter is the seperator, then start pushing the last word to the second stack
if (s[textIterator] == seperator)
{
wordAccumlator.Pop(); // to get ride of the sepertor character as we don't want to reverse it with the word
while (wordAccumlator.Count > 0)
textAccumlator.Push(wordAccumlator.Pop());
textAccumlator.Push(seperator); // add seperator after the word
}
else if (textIterator == 0) // at the end of the text, there is no seperator, but we need to push the last word
{
while (wordAccumlator.Count > 0)
textAccumlator.Push(wordAccumlator.Pop());
}

}
catch (Exception ex)
{
return "An error happened, " + ex.Message;
}
}
string result = string.Empty;
while (textAccumlator.Count > 0)
result = result + textAccumlator.Pop();
return result;
}

public static string ReverseWordsWithArray(string s, char seperator)
{
if (s == null)
return "Arguments error";
int length = s.Length;
char[] resultArray = new char[length];
int wordLength = 0; // counter for storing the last word length
for (int textIterator = 0; textIterator <= length; textIterator++)
{
try
{
// we will start processing the last word only if we see the seperator or this is the end of the string
if (textIterator == length || s[textIterator] == seperator)
{
// if this is the end of the string, we don't
if (textIterator < length)
resultArray[textIterator] = seperator;
for (int wordIterator = textIterator; wordIterator > textIterator - wordLength; wordIterator--)
{
//textIterator - wordLength represents the start location of the word
//(textIterator - wordIterator) represents a counter, 0, 1, 2 .. till wordLength
resultArray[textIterator - wordLength + (textIterator - wordIterator)] = s[wordIterator - 1];
}
wordLength = 0;
}
else
{
// we are still in the same word, increase word letters counter
wordLength = wordLength + 1;
}
}
catch (Exception ex)
{
return "An error happened, " + ex.Message;
}
}
string result = new string(resultArray);
return result;
}

No comments:

Post a Comment