c++ - 如何使用 C++ 计算字符串中的某个单词
问题描述
如何计算字符串中的相同单词
输入
字符串数
String1 = daddymathewdadreadad
String2 = sdgfghhjdjrjjyjjrtfdhe
搜索 = 爸爸
输出
string1 中的爸爸数 = 3
string2 中的爸爸数 = 0
代码:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string str[50];
int n;
cin>>n;
for(int i = 0; i < n;i++) {
cin>>str[i];
}
for(int i = 0; i < 50;i++) {
if(substr(i,4) == "dad"){
n += 1;
}
}
cout<<n;
return 0;
}
错误
在函数“int main()”中:[错误]“substr”未在此范围内声明
解决方案
您可以使用 的find()
成员函数std::string
,在每次成功查找后调整开始位置,直到字符串结束:
#include <string>
int count(const std::string& sentence, const std::string& word)
{
int total = 0;
size_t start = 0;
size_t pos = 0;
while ((pos = sentence.find(word, start)) != std::string::npos)
{
++total;
start = pos + word.size();
}
return total;
}
int main()
{
std::string input = "dadymathewdadreadady";
int c = count(input, "dad");
return 0;
}
推荐阅读
- python-3.x - 如何迭代熊猫数据帧并连接到另一个数据帧
- java - 如何使用 Powermock 模拟私有枚举?
- angular - 按下浏览器后退按钮后,CanDeactivate 防护未按预期运行
- java - 获取 ArrayList 的元素总和
- android - 如何在 Kotlin 中使用“getString()”从 Recycler Adapter 类访问“strings.xml”中的字符串
- angular - Angular 6,可观察的 JSON 属性顺序
- docker - 使用 Docker Compose 和 NGINX 的简单 PHP 应用程序无法在 ECS 上启动
- spring-webflux - spring-data-geode 和 spring-boot-starter-webflux 应用程序运行失败
- c# - c# stringbuilder - excel导出中的额外双引号
- envoyproxy - 我可以在运行时更改故障注入配置特使代理吗?