2010-05-24 163 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); 
     } 

    } 
} 

} 
相关问题