首页 > 解决方案 > 如何使用 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”未在此范围内声明

标签: c++dev-c++

解决方案


您可以使用 的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;
}

推荐阅读