Remove 2 or more blank spaces from a string in c#..?
what is the efficient mechanism to remove 2 or more white spaces from a 开发者_Go百科string leaving single white space.
I mean if string is "a____b" the output must be "a_b".
You can use a regular expression to replace multiple spaces:
s = Regex.Replace(s, " {2,}", " ");
Something like below maybe:
var b=a.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
var noMultipleSpaces = string.Join(" ",b);
string tempo = "this is a string with spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);
tempo = regex.Replace(tempo, @" ");
You Can user this method n pass your string value as argument you have to add one namespace also using System.Text.RegularExpressions;
public static string RemoveMultipleWhiteSpace(string str)
{
// A.
// Create the Regex.
Regex r = new Regex(@"\s+");
// B.
// Remove multiple spaces.
string s3 = r.Replace(str, @" ");
return s3;
}
精彩评论