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!

9 Responses to “Removing Additional White-Spaces in Sentence (C#)”

  1. JimShelley Says:

    Bob, that was just the thing I was looking for! Thank you so much!

  2. VIK Says:

    Thank you very much!

  3. Rod Howarth Says:

    Thanks heaps for this, just what I was after.

  4. Laura S Says:

    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+”,”");

  5. pavan Says:

    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

  6. pavan Says:

    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);


  7. 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);


Leave a Reply