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?
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, @" +", " ");
string.Join(" ","Hi! My name is troy and i love waffles!"
.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries)
.Select (s => s.Trim()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With