Removing Additional White-Spaces in Sentence (C#)
September 16, 2008
One of my co-workers asked me if I know on top of my head to remove additional white spaces in a sentence using C#. We all know that Trim() removes white spaces at front and end…. and “Replace” can be used to remove all white spaces in string BUT he dont want to remove all spaces …he just wants to remove extra spaces if any….
Input : This is a test sentence with some spaces
Desired Output : This is a test sentence with some spaces
Using RegEx here is the way, if you need it….
System.Text.RegularExpressions.Regex.Replace(input, @”\s+”, ” “);
Remember that this removes all whitespace characters including tabs, newlines etc… which is he wants anyway!
October 26, 2008 at 1:31 pm
nice!
December 11, 2008 at 12:06 pm
Bob, that was just the thing I was looking for! Thank you so much!
March 17, 2009 at 2:09 am
Thank you very much!
April 20, 2009 at 1:06 am
Thanks heaps for this, just what I was after.
July 7, 2009 at 5:28 pm
I tried this, in an input string, and it doesn’t work. Is this for text only?
nput = Console.ReadLine();
work = input.Trim();
input = work.Trim();
//test trying to get rid of excess white space
System.Text.RegularExpressions.Regex.Replace(input, @”\s+”,”");
July 8, 2009 at 11:12 pm
Nice!
July 16, 2009 at 5:32 am
hey this is not working for me.. m trying like this
string text = “select col. collegeName,col.cityId,col.grade, c.cityname, c.countryname, c.PinCode from collegeinfo col inner join city c on c.cityid=col.cityid”;
System.Text.RegularExpressions.Regex.Replace(text, @”\s+”,” “);
Console.WriteLine(text);
but finallay, it displays same string on console
July 16, 2009 at 5:32 am
string text = “select col. collegeName,col. cityId,col.grade, c. cityname, c.countryname, c.PinCode from collegeinfo col inner join city c on c.cityid= col.cityid”;
System.Text.RegularExpressions.Regex.Replace(text, @”\s+”,” “);
Console.WriteLine(text);
August 30, 2009 at 7:47 pm
Laura and Pavan… Remember that Strings are immutable in c#. So Regex.Replace returns you a new instance of modified string which is what you need.
string text = “select col. collegeName, col. cityId,col.grade, c. cityname, c.countryname, c.PinCode from collegeinfo col inner join city c on c.cityid= col.cityid”;
text = System.Text.RegularExpressions.Regex.Replace(text, @”\s+”,” “);
Console.WriteLine(text);