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.
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()
Regex.Replace(str, "[\s]+"," ")
Then call Trim to get rid of leading and trailing white space.
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.
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.
Regex rgx = new Regex("\\s+");
string str;
str=Console.ReadLine();
str=rgx.Replace(str," ");
str = str.Trim();
Console.WriteLine(str);