如何使用C++计算字符串中的特定单词
How to count certain word in string using C++
如何计算字符串中的同一个词
输入
字符串数
String1 = dadymathewdadreadad
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;
}
错误
In function 'int main()':
[Error] 'substr' was not declared in this scope
您可以在此处使用的一个技巧是将搜索词(例如 dad
)替换为空字符串,然后比较替换前后字符串的长度。
string input = "dadymathewdadreadady";
string search = "dad";
int size_orig = input.size();
replace(string, search, "");
cout << "number of 'dad' is: " << (size_orig - input.size()) / search.size();
可以使用std::string
的成员函数find()
,每次查找成功后调整起始位置,直到字符串结束:
#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;
}
其他解决方案:
#include <iostream>
#include <string>
using namespace std;
int main(){
int n;
string s[50];
int c;
cin>>n;
for (int i=0;i<n;i++){
cin>>s[i];
}
for (int i=0;i<n;i++) {
c=0;
int found=s[i].find("jack");
while(found!=string::npos){
found=s[i].find("jack",found+1);
if(found) c++;
}
cout<<c<<endl;
}
}
如何计算字符串中的同一个词
输入
字符串数
String1 = dadymathewdadreadad
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;
}
错误
In function 'int main()': [Error] 'substr' was not declared in this scope
您可以在此处使用的一个技巧是将搜索词(例如 dad
)替换为空字符串,然后比较替换前后字符串的长度。
string input = "dadymathewdadreadady";
string search = "dad";
int size_orig = input.size();
replace(string, search, "");
cout << "number of 'dad' is: " << (size_orig - input.size()) / search.size();
可以使用std::string
的成员函数find()
,每次查找成功后调整起始位置,直到字符串结束:
#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;
}
其他解决方案:
#include <iostream>
#include <string>
using namespace std;
int main(){
int n;
string s[50];
int c;
cin>>n;
for (int i=0;i<n;i++){
cin>>s[i];
}
for (int i=0;i<n;i++) {
c=0;
int found=s[i].find("jack");
while(found!=string::npos){
found=s[i].find("jack",found+1);
if(found) c++;
}
cout<<c<<endl;
}
}