C# 如何获得字母K的总出现次数?

C# 如何获得字母K的总出现次数?,c#,console,C#,Console,我想检查一下k出现了多少次。这是 到目前为止,我所做的并没有得到结果 class Program { static void Main(string[] args) { int count = 0; string str = "hnfdjkkedjjykukyukrtrnrkkkkt"; string l; for (int i = 0; i < str.Length; i++) {

我想检查一下k出现了多少次。这是 到目前为止,我所做的并没有得到结果

class Program
{
    static void Main(string[] args)
    {
        int count = 0;
        string str = "hnfdjkkedjjykukyukrtrnrkkkkt";
        string l;

        for (int i = 0; i < str.Length; i++)
        {
            l = str.Substring(1, 1);
            if (l == "k")
            {
                count++;
            }
        }
        Console.WriteLine("k appears " + count++ + " times");
        Console.ReadKey();
    }
}
类程序
{
静态void Main(字符串[]参数)
{
整数计数=0;
string str=“hnfdjkkedjykukukrntrkkkt”;
字符串l;
对于(int i=0;i
您可以尝试:

int count = str.Count(c => c=='k')
希望此帮助:-)

您可以尝试:

int count = str.Count(c => c=='k')

希望这有助于:-)

您可以简单地

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string s = "aasfkkfasfas";
        int count = s.Count(l => l== 'k');

        Console.WriteLine(count);
    }
}
为每个字母调用子字符串并不是最好的解决方案。请记住,字符串实现IEnumerable,因此您也可以这样做:

using System;

public class Program
{
    public static void Main()
    {
        string s = "aasfkkfasfas";
        int count = 0;
        foreach(char c in s)
        {
            if(c == 'k') 
                count++;
        }

        Console.WriteLine(count);
    }
}

这更接近于您的原始解决方案。

您可以使用

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string s = "aasfkkfasfas";
        int count = s.Count(l => l== 'k');

        Console.WriteLine(count);
    }
}
为每个字母调用子字符串并不是最好的解决方案。请记住,字符串实现IEnumerable,因此您也可以这样做:

using System;

public class Program
{
    public static void Main()
    {
        string s = "aasfkkfasfas";
        int count = 0;
        foreach(char c in s)
        {
            if(c == 'k') 
                count++;
        }

        Console.WriteLine(count);
    }
}

这更接近您的原始解决方案。

您也可以使用
RegEx
(正则表达式)来实现这一点,但对于您的用例来说,这有点过分了

它位于命名空间
System.Text.RegularExpressions
(请参阅)中

在你的情况下,应该是

Regex.Matches("hnfdjkkedjjykukyukrtrnrkkkkt", "[k]").Count

您也可以使用
RegEx
(正则表达式)来实现这一点,但对于您的用例来说,这有点过分了

它位于命名空间
System.Text.RegularExpressions
(请参阅)中

在你的情况下,应该是

Regex.Matches("hnfdjkkedjjykukyukrtrnrkkkkt", "[k]").Count

注意:要使用此代码,您必须包括
System.Linq
namespace确实感谢添加:-)注意:要使用此代码,您必须包括
System.Linq
namespace确实感谢添加:-)更改
l=str.Substring(i,1)和它应该工作这个工程fineChange
l=str.Substring(i,1)
应该可以工作这很好