Sunday, August 20, 2006

Reverse Words in C Sharp.NET

Lately I started some string manipulation in C Sharp, which you will see in the series to come. Please add your comments suggestions. These are optimized for performance

Input: Robert Frost
output is Frost Robert


public static string ReverseWord(string s)
{
int length = s.Length;
int i = 0;

string[] splittedArray = s.Split(' ');
StringBuilder sb = new StringBuilder();
for (i = splittedArray.Length - 1; i >= 0; i--)
{
if (i != 0)
sb.Append(splittedArray[i] + ' ');
else
sb.Append(splittedArray[i]);

}

return sb.ToString();
}


Here is another method to do the same using character array

public static string ReverseWordChar(string s)
{
int length = s.Length;
int i = 0,j=0;
StringBuilder sb= new StringBuilder();
int startPos = length - 1;

for (i = length-1; i >=0;i--)
{
if (s[i] == ' ')
{
for (j = i+1; j <= startPos; j++)
{
sb.Append(s[j]);
}
startPos = i;
sb.Append(' ');
}
}

for (j = 0; j < startPos; j++)
{
sb.Append(s[j]);
}

return sb.ToString();
}