0

I have a string "a ; b; c d; e"

How can I remove the white space around ";" but keep the one between chars. So after replacement, I want to get "a;b;c d;e"

Thanks

3
  • Split(";"c) your String and then remove the outer spaces with trim. Use a StringBuilder to concat the items together again. Commented Nov 16, 2010 at 22:38
  • @Time Schmelter, why use a StringBuilder when we have string.Join Commented Nov 16, 2010 at 22:41
  • @Tim Schmelter - You should probably post your answer as an actual answer so the questioner can accept it. Yours is clearly the best solution, in my opinion. Commented Nov 16, 2010 at 22:53

5 Answers 5

6

This would work if you only had one space before or after the ;

var clean = "a ; b; c d; e".Replace(" ;", ";").Replace("; ", ";");

If there could be multiple spaces before or after the ;, you could run it in a loop that's exit condition was when neither " ;" or "; " was found

Alternatively, a regex would work perfectly for this.

Sign up to request clarification or add additional context in comments.

1 Comment

Then what about if there is possiblly more than 1 whitespace around ";"
1
string source = "a ; b; c d; e";
string result = source.Replace(" ;", ";").Replace("; ", ";");

Comments

1

This will work for any number of spaces around the semi-colon:

var str = "a ; b; c d; e";
while (str.IndexOf("; ") > -1 || str.IndexOf(" ;") > -1) {
  str = str.Replace("; ", ";").Replace(" ;", ";");
}

Comments

1

Use a regular expression.

I've added code

function stripSpacesKeepSemicolons(string dirty) {
    private static Regex keepSemicolonStripSpacesRegex = new Regex("\\s*(;)\\s*");
    return keepSemicolonStripSpacesRegex.Replace(dirty,"$1");
}

7 Comments

I'm upvoting this because a Regex IS suited for this, there are just many Regex haters out there
This isn't very useful without at least a basic example or a link for more information. I could just as easily say "use the string BCL methods" but this probably wouldn't help the asker very much.
There should at least the Regex mentioned in the answer. I could ever say use the magic and it works ;)
Indeed, then just comment that he should provide it. Don't downvote with adding a CONSTRUCTIVE comment
I haven't downvote it. But i can understand that others have.
|
1

How about this:

  string s = "a ; b; c d; e";
  string x = String.Join(";", s.Split(';').Select(t => t.Trim()));

This should work regardless of the number of spaces involved.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.