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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | /// <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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | /// <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:
1 2 | string output=ReverseWordByWord("This is an eXclusiveMinds article"); Console.WriteLine(output); |
OUTPUT:
//input: This is an eXclusiveMinds article article eXclusiveMinds an is This |

Leave a Reply
You must be logged in to post a comment.