【问题标题】:How to count certain word in string using C++如何使用 C++ 计算字符串中的某个单词
【发布时间】:2019-11-15 07:24:53
【问题描述】:

如何计算字符串中的相同单词

输入

字符串数

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;
}

错误

在函数'int main()'中: [错误] 'substr' 未在此范围内声明

【问题讨论】:

  • std::string::find 是你的朋友
  • 您忘记在对象上调用substrstr.substr(i,4)。投票关闭为错字。你也可以cin &gt;&gt; str
  • @bolov str 是一个数组
  • 除了您遇到的错误外,您的代码还有 多个 问题。例如,n 是您应该阅读的字符串数,还是每个字符串中的匹配数?不可能两者同时存在。您也没有边界检查,无论是输入还是检查。
  • 请花一些时间刷新how to ask good questions,以及this question checklist。不清楚您是否询问错误以及如何修复它,或者您是否询问“[h]如何计算字符串中的相同单词”。

标签: c++ dev-c++


【解决方案1】:

您可以在这里使用的一个技巧是将搜索词(例如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();

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      其他解决方案:

      #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;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2020-08-08
        • 2014-01-02
        • 2012-09-23
        • 1970-01-01
        • 2020-12-03
        • 2023-03-21
        相关资源
        最近更新 更多