Monday, February 6, 2012

Reversing a string without creating a new string object in C#

A while ago i was asked to switch a group of words in the reverse order.  This was a simple task until they added the caveat that i could not create a new string object while switching the order of the words.  I searched the web and i really could not find a straight and complete way to accomplish this.  So i came out with my own way.  Not to say that it is the best way, but it is a way to do it.  I kept things simple to make it easier to understand. 

The first thing i do is create the string of words using the StringBuilder.  I defined a few variables to track the characters in the string.   My approach here was to first flip the whole string of characters.  In order to accomplish this i use a while loop and i start switching characters from the back to the front and from the front to the back until i get to the middle of the string.  It is important to stop in the middle or you will end up with the original string.



 

The next step is where the actual work happens.  Line 35 and 36 include a logic to look for the instance of blank spaces.  The blank spaces are the delimiters for each work in the full string.  

Lines 38-41 determines where the next word will end.  This is necessary since the last word must be determine. 

The while loop in lines 43-49 flip the letters in each word.  After the flipping is completed for the word, the outer loop moves forward to the next group of characters to continue the flipping process. 
 

 The final result illustrates flipping a group of words in the opposite way without creating different objects. 

You can imagine that there are many other ways to accomplish this task, but if someone ever ask you to perform this task with the minimum amount f string creation, you can use this.