2011-06-08 15 views
4

什麼是從字符串中移除2個或更多空格而留下單個空白空間的有效機制。從c#中的字符串中刪除2個或更多的空格。

我的意思是如果字符串是「a____b」,則輸出必須是「a_b」。

+0

你是問,如果有人不小心雙擊空格怎麼能糾正所有的實例?如果有3個空格, – 2011-06-08 06:00:51

回答

8

您可以使用正則表達式替換多個空格:

s = Regex.Replace(s, " {2,}", " "); 
+0

會執行此項工作嗎? 4,5? – 2011-06-08 06:03:14

+1

@尼克:是的。量詞'{2,}'使表達式匹配兩個或多個空格。 – Guffa 2011-06-08 06:04:40

+0

非常有效的機制 – Ajit 2011-06-08 06:07:36

2

類似下面可能:

var b=a.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries); 
var noMultipleSpaces = string.Join(" ",b); 
+0

這也是一個很好的方法,謝謝 – Ajit 2011-06-08 07:04:58

1
string tempo = "this is a  string with spaces"; 
RegexOptions options = RegexOptions.None; 
Regex regex = new Regex(@"[ ]{2,}", options);  
tempo = regex.Replace(tempo, @" "); 
0

您可以將用戶此方法N傳遞您的字符串值作爲參數 你必須添加一個也使用System.Text.RegularExpressions的命名空間;

公共靜態字符串RemoveMultipleWhiteSpace(字符串str)

{ 



    // A. 
    // Create the Regex. 
    Regex r = new Regex(@"\s+"); 

    // B. 
    // Remove multiple spaces. 
    string s3 = r.Replace(str, @" "); 
    return s3; 

}