How to trim whitespace between characters

Viewed 105804

How to remove whitespaces between characters in c#?

Trim() can be used to remove the empty spaces at the beginning of the string as well as at the end. For example " C Sharp ".Trim() results "C Sharp".

But how to make the string into CSharp? We can remove the space using a for or a for each loop along with a temporary variable. But is there any built in method in C#(.Net framework 3.5) to do this like Trim()?

9 Answers

If you want to keep one space between every word. You can do it this way as well:

string.Join(" ", inputText.Split(new char[0], StringSplitOptions.RemoveEmptyEntries).ToList().Select(x => x.Trim()));

if you want to remove all spaces in one word:

input.Trim().Replace(" ","")

And If you want to remove extra spaces in the sentence, you should use below:

input.Trim().Replace(" +","")

the regex " +", would check if there is one ore more following space characters in the text and replace them with one space.

var str="  c sharp  "; str = str.Trim();
        str = Regex.Replace(str, @"\s+", " ");  ///"c sharp"
Related