Remove spaces inside a string

Hey guys i have lines like this

"This_ ___ is_a _ _string."

and I want to turn all multiple spaces into one. Are there any functions in C # that can do this?

thanks

+6
source share
4 answers
var s = "This is a string with multiple white space"; Regex.Replace(s, @"\s+", " "); // "This is a string with multiple white space" 
+11
source
 Regex r = new Regex(@"\s+"); string stripped = r.Replace("Too many spaces", " "); 
+5
source

Here's a good way without regex. With Linq.

 var astring = "This is a string with to many spaces."; astring = string.Join(" ", astring.Split(' ').Where(m => m != string.Empty)); 

output "This is a string with to many spaces"

+3
source

The examples of regular expressions on this page are probably good, but here is a solution without a regular expression:

 string myString = "This is a string."; string myNewString = ""; char previousChar = ' '; foreach(char c in myString) { if (!(previousChar == ' ' && c == ' ')) myNewString += c; previousChar = c; } 
+2
source

Source: https://habr.com/ru/post/886213/


All Articles