How to replace multiple spaces with single space?

六眼飞鱼酱① 提交于 2021-02-07 10:54:31

问题


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 !!!

回答1:


You can match the following:

@"\s+"

and replace with:

" "

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



回答2:


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,}"," ");


来源:https://stackoverflow.com/questions/23800371/how-to-replace-multiple-spaces-with-single-space

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!