2010-05-24 162 views

回答

16

下面是使用LINQ(使用擴展方法寫的)版本:

int s = str.Where(c => c == 's').Count(); 

這使用的事實,stringIEnumerable<char> ,因此我們可以過濾所有與您正在查找的字符相同的字符,然後計算所選元素的數量。事實上,你可以寫眼前這個(因爲Count方法允許你指定應適用於所有的計算元素謂語):

int s = str.Count(c => c == 's'); 
+0

我試圖在VS2008和字符串似乎並沒有被IEnumerable的。 你可以驗證。 string.ToCharArray()是IEnumerable – josephj1989 2010-05-24 22:01:48

+0

@ josephj1989,再次檢查... http://msdn.microsoft.com/en-us/library/system.string.aspx – 2010-05-24 22:23:07

+2

爲了使Intellisense爲您提供LINQ擴展方法,您可能必須將該字符串轉換爲'IEnumerable '。 – Phong 2010-05-25 00:43:53

2
for(int i=0; i < str.Length; i++) { 
    if(str[i] == myChar) { 
     charCount++; 
    } 
} 
3
s.Where(c => c == 's').Count() 

給出s是一個字符串,你正在尋找的「

1
 string s = "sasysays "; 
     List<char> list = s.ToList<char>(); 
     numberOfChar = list.Count<char>(c => c=='s'); 
7

另一種選擇是:

int numberOfS = str.Count('s'.Equals); 

這是一個小的向後 - 's'是一個字符,每個字符都有一個Equals方法,它可以用作Count的參數。
當然,這不如c => c == 's'靈活 - 你不能平凡地將它改變成複雜的條件。

+0

+1,相當聰明...... – 2010-05-24 22:20:36

+1

絕對聰明,雖然肯定比寫出'c => c =='s''更直觀(我認爲代碼更可能導致暫停)。 – Phong 2010-05-25 00:45:49

2

一個更通用的解決方案,計算所有字符的出現次數:

var charFrequencies = new Dictionary<char, int>(); 
foreach(char c in s) 
{ 
    int n; 
    charFrequencies.TryGetValue(c, out n); 
    n++; 
    charFrequencies[c] = n; 
} 

Console.WriteLine("There are {0} instances of 's' in the string", charFrequencies['s']); 
+0

不錯的是,這是非常可能的不止一個字母是必要的,並計算一次是一個好主意。你也可以編寫's.GroupBy(c => c).ToDictionary(g => g.Key,g => g.Count());'來實現同一個字典。我可能使用了太多的LINQ':P' – Kobi 2010-05-25 04:07:41

0

試試這個代碼:

namespace Count_char 
{ 
    class Program 
    { 
    static void Main(string[] args) 
    { 
     string s1 = Convert.ToString(Console.ReadLine()); 
     for (int i = 97; i < 123; i++) 
     { 
      string s2 = Convert.ToString(Convert.ToChar(i)); 

      CountStringOccurrences(s1, s2); 
     } 


     Console.ReadLine(); 
    } 
    public static void CountStringOccurrences(string text, string pattern) 
    { 

     int count = 0; 
     int i = 0; 
     while ((i = text.IndexOf(pattern, i)) != -1) 
     { 
      i += pattern.Length; 
      count++; 

     } 
     if (count != 0) 
     { 
      Console.WriteLine("{0}-->{1}", pattern, count); 
     } 

    } 
} 

} 
相關問題