Reverse words in a string in C#

Let the input string be “i like this program very much”. The function should change the string to “much very program this like i”.

class Reverse_Words_In_String
{
static void Main(string[] args)
{
Console.WriteLine(“Please enter a string: “);
string strInput = Console.ReadLine();
List strList = strInput.SplitThisString();
int start = 0, end = strList.Count() – 1;
string strTemp = string.Empty, strReverse = string.Empty;
while (true)
{
if (start >= end)
{
break;
}
else
{
strTemp = strList[end];
strList[end] = strList[start];
strList[start] = strTemp;
++start;
–end;
}
}

strReverse = string.Join(” “, strList.ToArray());
Console.WriteLine(“Reverse string is: {0}”, strReverse);
Console.ReadKey();
}
}

public static partial class StringExtensionMethods
{
public static List SplitThisString(this string str)
{
int start = 0;
List<string> list = new List<string>();
for (int i = 0; i < str.Length; ++i)
{
if (str[i] == ‘ ‘)
{
list.Add(str.Substring(start, i + 1 – start));
start = i + 1;
}

if (i + 1 == str.Length)
{
list.Add(str.Substring(start, i + 1 – start));
}
}
return list;
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s