Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim " a b c " into "a b c" [duplicate]

Tags:

c#

.net

algorithm

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.

like image 923
Cartesius00 Avatar asked Apr 09 '12 08:04

Cartesius00


5 Answers

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);
like image 119
Henk Holterman Avatar answered Nov 17 '22 03:11

Henk Holterman


You could use Regex for this:

Regex.Replace(my_string, @"\s+", " ").Trim();
like image 23
ionden Avatar answered Nov 17 '22 04:11

ionden


Regex.Replace(my_string, @"^\s+|\s+$|(\s)\s+", "$1");
like image 22
Lucero Avatar answered Nov 17 '22 04:11

Lucero


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,}", " ");
like image 4
Guffa Avatar answered Nov 17 '22 03:11

Guffa


You can do a

Regex.Replace(str, "\\s+", " ").Trim()

http://msdn.microsoft.com/en-us/library/e7f5w83z.aspx

like image 2
Cristian Toma Avatar answered Nov 17 '22 03:11

Cristian Toma