简体   繁体   中英

replace blank spaces before first word in string, then remove extra blank spaces

I have strings like:

string stuff = "    this    is    something you could    use one day";

I am using following function to remove extra blank spaces:

private string removeThem(string str) { 
    if (str!= null){
        return  Regex.Replace(str, @"\s+", " "); 
    }else{
        return "";
    }
}

so after applying that function I get:

" this is something you could use one day"

but I want:

"this is something you could use one day"

How to do it?

You can easily just run a Trim() after running the Regex.Replace() :

string str = str.Trim();

But if you want a single regex to remove consecutive spaces and trim trailing spaces, you could try this regex:

^\s+|\s+$|\s+(?=\s)

Replace by nothing.

^\\s+ matches all spaces at the beginning of the string;

\\s+$ matches all spaces at the end of the string;

\\s+(?=\\s) will match all consecutive spaces and leave one.

I would just avoid RegEx entirely - they are almost always hard to maintain. If there is a more direct option I'd use that.

How about this:

private string removeThem(string str)
{ 
    return String.Join(" ", (str ?? "").Split(new [] { ' ' },
        StringSplitOptions.RemoveEmptyEntries));
}

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