RSS

Program to reverse sentence word by word using C#

Wed, Dec 9, 2009

Inverview Tips, Programming, Tutorials

This example shows how can we reverse a sentence word by word. For example; If we have string “This is an eXclusiveMinds article” output should be “article eXclusiveMinds an is This”. For this we have two methods ReverseWordByWord and Reverse (this is helper method to reverse string character by character).
This is also one of the most frequently asked interview question in Microsoft, Google and Amazon for position of Software Design/Development Engineer (or Test).

/// <summary>
/// Function to reverse sentence word by word
/// </summary>
/// <param name="sentence">string (sentence)</param>
/// <returns>reversed string by word</returns>
public string ReverseWordByWord(string sentence)
{
	char[] str = sentence.ToCharArray();
 
	str = Reverse(str, 0, str.Length - 1);
 
	int start = 0, end = 0;
	for (int i = 0; i < str.Length; i++)
	{
		if (str[i] == ' ')
		{
			end = i - 1;
			str = Reverse(str, start, end);
			start = i + 1;
		}
	}
 
	//For Last word
	end = str.Length - 1;
	str = Reverse(str, start, end);
 
	return new string(str);
}

This method is helper function which will reverse a string character by character.

/// <summary>
/// Helper method to reverse string character by character.
/// </summary>
/// <param name="str">string to be reversed</param>
/// <param name="start">start index</param>
/// <param name="end">end index</param>
/// <returns>reversed string</returns>
public char[] Reverse(char[] str, int start, int end)
{
	while (end > start)
	{
		str[start] ^= str[end];
		str[end] ^= str[start];
		str[start] ^= str[end];
		end--;
		start++;
	}
	return str;
}

Testing This Method:

string output=ReverseWordByWord("This is an eXclusiveMinds article");
Console.WriteLine(output);

OUTPUT:

//input: This is an eXclusiveMinds article
article eXclusiveMinds an is This
Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Related Posts:

, , , ,

This post was written by:

eXclusiveMinds - who has written 500 posts on eXclusiveMinds.


Contact the author

Leave a Reply

You must be logged in to post a comment.