Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim whitespace characters from within a string

I have a string with an unknown combination of whitespace characters (\t, \n or space) between words. For example:

string str = "Hello \t\t  \n \t    \t World! \tPlease Help.";

I want to replace each sequence of inner whitespace characters with a single space:

string str = "Hello World! Please Help.";

Does .NET provide a built-in way to do this? If not, how can I do this via C#?

like image 407
BlackJack Avatar asked Dec 21 '22 01:12

BlackJack


2 Answers

using System.Text.RegularExpressions;

newString = Regex.Replace(oldString, @"\s+", " ");
like image 199
John Pick Avatar answered Dec 24 '22 00:12

John Pick


Try the following regex replacement

string original = ...;
string replaced = Regex.Replace(original, @"\s+", " ");

This replace each group of white space characters (\s) with a single space. You can find other helpful character groups here

  • http://msdn.microsoft.com/en-us/library/4edbef7e(v=vs.71).aspx
like image 41
JaredPar Avatar answered Dec 24 '22 00:12

JaredPar