Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove space from String

Tags:

c#

I have a lot of strings that look like this:

current            affairs

and i want to make the string be :

current affairs

i try to use Trim() but it won't do the job

like image 681
YosiFZ Avatar asked Dec 05 '22 16:12

YosiFZ


2 Answers

Regex can do the job

string_text = Regex.Replace(string_text, @"\s+", " ");
like image 73
Shakti Singh Avatar answered Dec 10 '22 11:12

Shakti Singh


You can use regular expressions for this, see Regex.Replace:

var normalizedString = Regex.Replace(myString, " +", " ");

If you want all types of whitespace, use @"\s+" instead of " +" which just deals with spaces.

var normalizedString = Regex.Replace(myString, @"\s+", " ");
like image 43
Oded Avatar answered Dec 10 '22 09:12

Oded