计算字符串中的字符串

Counting a String within a string

本文关键字:字符串 计算      更新时间:2023-10-16

我被告知要用户提供一个字符串(一个句子)。然后要求用户输入另一个字符串以在字符串 1(句子)中搜索。程序必须计算第二个字符串在第一个字符串中出现的次数。我没有收到任何错误,但它没有计算字母。这是我得到的结果:

输入一句话:我爱吃汤

输入要搜索的字符串:ou

您提供的第一个字符串中有 0 个字符串 ou。

有人可以告诉我我做错了什么吗?我是 c++ 的初学者,所以我在理解方面遇到了一些麻烦。

#include <iostream>
#include <string>
using namespace std;
int  main() {
        string sentence;
        string search;
        int count = 0;
        cout<<"Enter a sentence:";
        getline (cin, sentence);
        cout<<"Enter string to search:";
        getline (cin, search);
        cout << "There are " << count << " of the string " << search << " in the first string you provided." <<"n";
        for (int i=0; i < sentence.size(); ++i)
        {
                if (sentence == search)
                count++;
        }
        return count;

}

两个问题:

  1. 在计算之前打印count
  2. 您实际上并不是在搜索子字符串。您应该查看std::string的文档,以找到搜索子字符串的适当方法。但是,您走在正确的轨道上。

好吧,您正在尝试在计算结果之前输出结果。

此外,==用于完全匹配,而不是子字符串搜索。

在循环之后有 cout 打印行,您可以在其中搜索字符串并设置计数。 将其移动到该循环下方。

看起来你应该把cout语句放在此方法的末尾。因为在代码中,输出时计数始终为 0

你应该修改你的循环,以便它真正搜索子字符串并计算它们的出现次数:

string::size_type pos = sentence.find(search);
while (pos != string::npos)
{
    pos = sentence.find(search, pos + search.size());
    count++;
}

此外,您很可能希望将此行移动到实际计算count值的点之后

cout << "There are " << count << ...

否则,它显然会输出最初初始化count的值(即 0 )。