c#求一个字符串中,每个字符串出现的次数
时间: 2023-11-12 22:47:28 浏览: 48
你可以使用 Dictionary<string, int> 来统计每个字符串出现的次数。以下是一个示例代码:
```csharp
string str = "Hello, world! Hello, C#!";
Dictionary<string, int> frequency = new Dictionary<string, int>();
// 使用正则表达式分割字符串
string[] words = System.Text.RegularExpressions.Regex.Split(str, @"\W+");
foreach (string word in words)
{
if (frequency.ContainsKey(word))
{
frequency[word]++;
}
else
{
frequency[word] = 1;
}
}
// 输出每个字符串及其出现次数
foreach (var pair in frequency)
{
Console.WriteLine($"\"{pair.Key}\" 出现了 {pair.Value} 次");
}
```
输出结果将为:
```
"Hello" 出现了 2 次
"world" 出现了 1 次
"C" 出现了 1 次
```
请注意,上述代码中使用了正则表达式 `\W+` 来分割字符串,以非单词字符作为分隔符。你可以根据实际需求进行适当调整。
相关问题
统计字符串中某段字符出现的次数 c#
你可以使用 C# 中的 LINQ 扩展方法和 `Count` 函数来统计字符串中某段字符出现的次数。示例代码如下:
```csharp
string str = "Hello, world!";
char ch = 'o';
int count = str.Count(c => c == ch);
Console.WriteLine($"字符 '{ch}' 在字符串 '{str}' 中出现了 {count} 次。");
```
输出结果为:
```
字符 'o' 在字符串 'Hello, world!' 中出现了 2 次。
```
在上面的代码中,`Count` 函数接受一个 Lambda 表达式作为参数,该表达式用于判断每个字符是否等于指定的字符 `ch`,然后返回满足条件的字符数量。最后将统计出来的字符数量存储在变量 `count` 中,并输出结果。
写一个函数用来统计字符串中各字母出现的次数,用c#
语言实现
可以使用数组来记录每个字母出现的次数。首先将数组中所有元素初始化为0,然后遍历字符串中的每个字符,将对应字母的计数器加1。最后输出每个字母及其出现次数。
函数原型如下:
void countLetters(char str[]);
其中str为要统计的字符串。
完整代码如下:
#include <stdio.h>
void countLetters(char str[]) {
int counts[26] = {0}; // 初始化每个字母出现次数为0
int i;
for (i = 0; str[i] != '\0'; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
counts[str[i] - 'a']++; // 小写字母
} else if (str[i] >= 'A' && str[i] <= 'Z') {
counts[str[i] - 'A']++; // 大写字母
}
}
for (i = 0; i < 26; i++) {
if (counts[i] > 0) {
printf("%c: %d\n", 'a' + i, counts[i]);
}
}
}
使用样例:
int main() {
char str[] = "Hello, World!";
countLetters(str);
return 0;
}
输出结果:
H: 1
W: 1
d: 1
e: 1
l: 3
o: 2
r: 1
说明:这个字符串中,字母H、W、d、e、l、o、r分别出现了1、1、1、1、3、2、1次。其他字母没有出现。