📜  如何在c#中计算字母(1)

📅  最后修改于: 2023-12-03 15:08:52.054000             🧑  作者: Mango

如何在C#中计算字母

在C#中,计算字母的主要是依靠字符串操作。下面介绍几种常见的计算方式。

计算字符串中某个字符的出现次数

可以使用Regex.Matches()方法和正则表达式来匹配字符串中某个字符的出现次数。

using System.Text.RegularExpressions;

string input = "Hello, World!";
char targetChar = 'o';
int count = Regex.Matches(input, targetChar.ToString()).Count;

Console.WriteLine($"The count of '{targetChar}' in '{input}' is {count}");
// 输出:"The count of 'o' in 'Hello, World!' is 2"
计算字符串中所有字符的出现次数

可以使用Dictionary<char, int>来统计字符串中所有字符的出现次数。遍历字符串中的每个字符,如果已经在字典中出现过,则将其对应的值加1,否则将其添加到字典中,值为1。

string input = "Hello, World!";
Dictionary<char, int> charCount = new Dictionary<char, int>();

foreach (char c in input)
{
    if (charCount.ContainsKey(c))
    {
        charCount[c]++;
    }
    else
    {
        charCount.Add(c, 1);
    }
}

foreach (var kvp in charCount)
{
    Console.WriteLine($"The count of '{kvp.Key}' is {kvp.Value}");
}
/* 输出:
The count of 'H' is 1
The count of 'e' is 1
The count of 'l' is 3
The count of 'o' is 2
The count of ',' is 1
The count of ' ' is 1
The count of 'W' is 1
The count of 'r' is 1
The count of 'd' is 1
The count of '!' is 1
*/
计算字符串中不同字符的数量

可以使用HashSet<char>来记录字符串中出现过的不同字符,最后返回集合的大小即可。

string input = "Hello, World!";
HashSet<char> distinctChars = new HashSet<char>();

foreach (char c in input)
{
    distinctChars.Add(c);
}

int count = distinctChars.Count;
Console.WriteLine($"The count of distinct chars in '{input}' is {count}");
// 输出:"The count of distinct chars in 'Hello, World!' is 10"
计算字符串中字母的出现次数

可以使用char.IsLetter()方法判断一个字符是否是字母,然后和上面的方法类似,统计出现次数即可。

string input = "Hello, World!";
Dictionary<char, int> letterCount = new Dictionary<char, int>();

foreach (char c in input)
{
    if (char.IsLetter(c))
    {
        if (letterCount.ContainsKey(c))
        {
            letterCount[c]++;
        }
        else
        {
            letterCount.Add(c, 1);
        }
    }
}

foreach (var kvp in letterCount)
{
    Console.WriteLine($"The count of '{kvp.Key}' is {kvp.Value}");
}
/* 输出:
The count of 'H' is 1
The count of 'e' is 1
The count of 'l' is 3
The count of 'o' is 2
The count of 'W' is 1
The count of 'r' is 1
The count of 'd' is 1
*/

以上就是在C#中计算字母的几种常见方法。