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.
You could use Regex
for this:
Regex.Replace(my_string, @"\s+", " ").Trim();
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);
\s
this will only remove space (U+0020) characters, not other characters classified as whitespace. This meets to the Q's criterion but in practice I would expect any such need to also apply to tabs etc. - Richarddelimiters = null
corresponds to \s
- Henk HoltermanTrim()
into the mix but uses the regex to do it all. (Not that I care much, I capped the 200 reps for today several hours ago...) - Lucero
Regex.Replace(my_string, @"^\s+|\s+$|(\s)\s+", "$1");
.Trim()
is so much more concise, it's easier to maintain. (I'm not downvoting, though - this version may be preferred in some situations, like a tight loop, if it really is faster) - Izkata
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()
Regex rgx = new Regex("\\s+");
string str;
str=Console.ReadLine();
str=rgx.Replace(str," ");
str = str.Trim();
Console.WriteLine(str);
Use a regular expression:
"( ){2,}" //Matches any sequence of spaces, with at least 2 of them
and use that to replace all matches with " ".
I haven't done it in C# and I need more time to figure out what the documentation says, so you'll have to find that by yourself.. sorry.
use regex
String test = " a b c ";
test = Regex.Replace(test,@"\s{2,}"," ");
test = test.Trim();
this code replace any 2 or more spaces with one space using Regex
then remove in the beginning and the end.
\s{2,}
or \s\s+
or even \s+
if you want to replace any number of whitespace by a space (note that since \s
does match all whitespace including characters such as tabs the result will be different). - Lucero
Regex.Replace(str, "[\s]+"," ")
Then call Trim to get rid of leading and trailing white space.
.Trim()
for that. :) - naveen