简体   繁体   中英

How to replace multiple spaces with single space?

I am developing web app using C#. I want to replace multiple spaces with single space in between string. I tried with normal string replace function, but it was not helpful. It is possible with Regular Expression, but I don't have clear idea about that. Please provide a example code for the following string:

Actual String:

Have       a   Nice              Day !  !!

Needed:

Have a Nice Day !!!

You can match the following:

@"\\s+"

and replace with:

" "

Regex.Replace("Have       a   Nice              Day !  !!", @"\s+", " ");

See if there are two or more spaces exist, if so replace it with single space.

var subject = "Have       a   Nice              Day !  !!";
var result = Regex.Replace(subject,@"\s{2,}"," ");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM