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#?
using System.Text.RegularExpressions;
newString = Regex.Replace(oldString, @"\s+", " ");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With