统计字符串中某段字符出现的次数 c#
时间: 2023-08-30 14:06:25 浏览: 60
你可以使用 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` 中,并输出结果。
相关问题
统计字符串中某字符出现次数
好的,可以为您提供一个 Python 的例子:
```python
def count_char(s, c):
"""
统计字符串 s 中字符 c 出现的次数
"""
count = 0
for ch in s:
if ch == c:
count += 1
return count
```
其中,`s` 为要统计的字符串,`c` 为要查找的字符。函数遍历整个字符串,每当找到一个字符与 `c` 相等时,计数器 `count` 就加 1。最后返回计数器的值即可。
C++ 统计字符串中某字符出现的次数
可以循环遍历字符串中的每一个字符,然后判断是否和目标字符相等,如果相等计数器加一。这里提供一个示例代码:
```C++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
char target = 'o';
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == target) {
count++;
}
}
cout << target << " appears " << count << " times in the string." << endl;
return 0;
}
```
输出结果为:
```
o appears 2 times in the string.
```