Possible Duplicate:
How do I replace multiple spaces with a single space in C#?
What is the most elegant way how to trim whitespace in strings like " a<many spaces>b c "
into "a b c"
. So, repeated whitespace is shrunk into one space.
A solution w/o regex, just to have it on the table:
char[] delimiters = new char[] { ' '}; // or null for 'all whitespace'
string[] parts = txt.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string result = String.Join(" ", parts);
You could use Regex
for this:
Regex.Replace(my_string, @"\s+", " ").Trim();
Regex.Replace(my_string, @"^\s+|\s+$|(\s)\s+", "$1");
Use the Trim
method to remove whitespace from the beginning and end of the string, and a regular expression to reduce the multiple spaces:
s = Regex.Replace(s.Trim(), @"\s{2,}", " ");
You can do a
Regex.Replace(str, "\\s+", " ").Trim()
http://msdn.microsoft.com/en-us/library/e7f5w83z.aspx
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