统计字符串中字符串出现的次数cpp
时间: 2023-11-16 10:04:12 浏览: 59
您好,可以为您解答问题。统计字符串中字符串出现的次数可以通过遍历字符串,依次搜索子字符串,再尝试匹配的方式来实现。以下是一段 C++ 代码示例:
```cpp
// 统计字符串中字符串出现的次数
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "This is a test sentence. It contains the word test twice.";
string searchStr = "test";
int count = 0;
size_t pos = str.find(searchStr); // 查找子字符串第一次出现的位置
while (pos != string::npos) // 如果存在子字符串
{
count++; // 子字符串出现次数+1
pos = str.find(searchStr, pos + 1); // 继续查找下一次子字符串出现的位置
}
cout << "The string \"" << searchStr << "\" appears " << count << " times in the string." << endl;
return 0;
}
```
希望能够帮到您,谢谢!
相关问题
编程题 统计字符串出现的次数
题目描述:
给定一个字符串 `s` 和一个目标字符串 `target`,统计 `target` 在 `s` 中出现的次数。
示例:
输入:s = "hello world", target = "o"
输出:2
解释:'o' 在 "hello world" 中出现了 2 次。
思路:
遍历字符串 `s`,统计每个字符出现的次数,最后统计目标字符串 `target` 出现的次数即可。
代码实现(Python):
```python
def count_target(s: str, target: str) -> int:
count = 0
for c in s:
if c == target:
count += 1
return count
s = "hello world"
target = "o"
print(count_target(s, target)) # 输出 2
```
代码实现(C++):
```cpp
#include <iostream>
#include <string>
using namespace std;
int count_target(string s, char target) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == target) {
count++;
}
}
return count;
}
int main() {
string s = "hello world";
char target = 'o';
cout << count_target(s, target) << endl; // 输出 2
return 0;
}
```
用c++写统计某个字符在字符串中出现的次数
可以使用 C++ 的字符串(string)类和循环结构实现统计某个字符在字符串中出现的次数。具体实现如下:
```cpp
#include <iostream>
#include <string>
using namespace std;
int countChar(string str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == c) {
count++;
}
}
return count;
}
int main() {
string str = "Hello, World!";
char c = 'o';
int count = countChar(str, c);
cout << "The character '" << c << "' appears " << count << " times in the string." << endl;
return 0;
}
```
在上面的代码中,我们定义了一个 `countChar` 函数,它接收两个参数:一个字符串和一个字符。该函数使用循环结构遍历字符串中的每个字符,如果当前字符等于要统计的字符,就将计数器加 1。最后,函数返回计数器的值。
在 `main` 函数中,我们定义了一个字符串 `str` 和一个字符 `c`,然后调用 `countChar` 函数统计字符 `c` 在字符串 `str` 中出现的次数,并将结果输出到控制台。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)