2014-10-18 19 views
0

是否有一種方法可以使用.Replace("a", "A");獲取替換次數?獲取替換次數

Example: 

String string_1 = "a a a"; 
String string_2 = string_1.Replace("a", "A"); 

在這種情況下,輸出應該是3,因爲aA3次取代。

+0

重複顯示了幾種方法來計算字符串的發生,但不是如何用'String.Replace'來執行它(因爲你不能)。 – 2014-10-18 17:03:59

回答

3

可以使用.Split功能得到計數:

string_1.Split(new string[] { "a" }, StringSplitOptions.None).Length-1; 

分割字符串後,我們會得到一個項目的更多。因爲,.Split函數返回一個字符串數組,其中包含此字符串中由指定字符串數組的元素分隔的子字符串。因此,Length財產的價值將是n + 1

+0

爲什麼你在最後加上'-1'? – Isamu 2014-10-18 17:02:42

+0

長度始終爲(O)1。 http://msdn.microsoft.com/en-us/library/system.array.length(v=vs.110).aspx – 2014-10-18 17:05:12

+0

@Isamu因爲一個「a」會產生兩個字符串,所以你必須減去1得到正確的計數。 – 2014-10-18 17:05:19

1

您可以使用Regex.Matches方法找出將被替換的內容。使用Regex.Escape方法可以將字符串轉義,如果它包含任何將被專門處理爲正則表達式的字符。

​​
3

你不能直接與string.replace做到這一點,但你可以使用string.IndexOf來搜索您的字符串,直到不能找到匹配

int counter = 0; 
int startIndex = -1; 
string string_1 = "a a a"; 
while((startIndex = (string_1.IndexOf("a", startIndex + 1))) != -1) 
    counter++; 
Console.WriteLine(counter); 

如果這成爲頻繁用那麼你可以計劃創建extension method

public static class StringExtensions 
{ 
    public static int CountMatches(this string source, string searchText) 
    { 

     if(string.IsNullOrWhiteSpace(source) || string.IsNullOrWhiteSpace(searchText)) 
      return 0; 

     int counter = 0; 
     int startIndex = -1; 
     while((startIndex = (source.IndexOf(searchText, startIndex + 1))) != -1) 
      counter++; 
     return counter; 
    } 
} 

叫它

IndexOf的優點在於您無需創建字符串(Split)或對象數組(Regex.Matches)的數組。這只是一個普通的香草循環,涉及整數。