Sunday, 6 April 2014

How to Remove Unwanted Whitespace(s) between Words in C#

When dealing with user input (especially on web), we do not have control over some strange things. One common issue when user enter text, places too many spaces between words. A lot of times this is due to some copy and paste issue such as a user pasting text from a Microsoft Word document.

The common thought might be to add a bunch of replace methods to replace 2 spaces with 1, 3 spaces with 1, 4 spaces with 1, etc. Something like this :

enteredString = enteredString.Replace("  ", " ");
enteredString = enteredString.Replace("   ", " ");
enteredString = enteredString.Replace("    ", " ");


The main issue here is that you need to know in advance, for how many spaces you are looking to make this work correctly. For Example :-  In above case, if the string had more than 4 spaces, then things get disorderly. we could manually parse the string character by character, use peek and compare to find and remove spaces but there is actually an easier way to do this.


Using the method below, no matter how many spaces together in the string, this method will remove them and replace with a single space.

 public static string MoveOutExtraSpace(string enteredString)
 {
     enteredString = enteredString.Replace(" ", "()");
     enteredString = enteredString.Replace(")(", "");
     enteredString = enteredString.Replace("()", " ");
     enteredString = enteredString.Trim(); // for start and end space
     return enteredString;
 }

That’s it!!…..Happy Programming...

No comments:

Post a Comment