2012-04-18 68 views
4

刪除的空間,我有很多的字符串看起來像這樣:從字符串

current   affairs 

,我想使字符串是:

current affairs 

我嘗試使用Trim(),但它贏得了」做T的工作

+2

只是爲了將來參考,修剪()從一開始就刪除空間並僅在字符串結束。 – Archer 2012-04-18 10:33:29

回答

11

正則表達式可以做的工作

string_text = Regex.Replace(string_text, @"\s+", " "); 
+5

或者,作爲一個更快的變體:'Regex.Replace(myString,「\\ s {2,}」,「」)''所以你不能自己替換單個空格。在我的測試中,差異約爲30%。 – Joey 2012-04-18 10:32:57

6

您可以使用正則表達式的資料可以看Regex.Replace

var normalizedString = Regex.Replace(myString, " +", " "); 

如果您想要所有類型的空格,請使用@"\s+"而不是" +",它只處理空格。

var normalizedString = Regex.Replace(myString, @"\s+", " "); 
0

使用正則表達式。

yourString= Regex.Replace(yourString, @"\s+", " "); 
0

您可以使用正則表達式:

public string RemoveMultipleSpaces(string s) 
{ 
    return Regex.Replace(value, @"\s+", " "); 
} 

後:

string s = "current   affairs "; 
s = RemoveMultipleSpaces(s); 
-1

首先,你需要分割整個字符串,然後應用修剪到每個項目。

string [] words = text.Split(' '); 
    text=""; 
    forearch(string s in words){ 
    text+=s.Trim(); 
    } 
    //text should be ok at this time 
0

使用正則表達式這裏是這樣的,

System.Text.RegularExpressions.Regex.Replace(input, @」\s+」, 」 「); 

這將刪除所有空白字符,包括製表符,換行符等