我被告知要向用户询问一个字符串(一个句子)。然后要求用户输入另一个字符串以在字符串 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;
}
最佳答案
两个问题:
- 在计算之前打印
count
。 - 您实际上并不是在搜索子字符串。您应该查看
std::string
的文档找到一种合适的方法来搜索子串。但是,您走在正确的轨道上。
关于c++ - 计算字符串中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14616593/