Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String whitespace

Tags:

string

c#

I have a string that will have multiple whitespace characters in it and I'm wanting to seperate each word by 1 whitespace character. Say if the string is "Hi! My name is troy        and      i love                 waffles!", I want to trim that so it is "Hi! My name is troy and I love waffles!". How would I do this?

like image 671
tr0yspradling Avatar asked Jun 20 '26 14:06

tr0yspradling


2 Answers

Use the regular expression \s+ (one or more whitespace) with the Regex.Replace method from the System.Text.RegularExpressions namespace:

s = Regex.Replace(s, @"\s+", " ");

If you just want to replace spaces you can change the "\s" to a space "":

s = Regex.Replace(s, @" +", " ");
like image 158
Mark Byers Avatar answered Jun 22 '26 04:06

Mark Byers


string.Join(" ","Hi! My name is troy        and      i love                 waffles!"
    .Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries)
    .Select (s => s.Trim()))
like image 40
asawyer Avatar answered Jun 22 '26 02:06

asawyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!