edgarmtze
edgarmtze

Reputation: 25048

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?

Upvotes: 0

Views: 2732

Answers (2)

Enigmativity
Enigmativity

Reputation: 117064

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

Upvotes: 2

Jerry
Jerry

Reputation: 71538

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.

Upvotes: 4

Related Questions