计算字符串中的字符串
Counting a String within a string
我被告知要用户提供一个字符串(一个句子)。然后要求用户输入另一个字符串以在字符串 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
的文档,以找到搜索子字符串的适当方法。但是,您走在正确的轨道上。
好吧,您正在尝试在计算结果之前输出结果。
此外,==
用于完全匹配,而不是子字符串搜索。
在循环之后有 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
)。
相关文章:
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 通过字符串来计算长度需要更长的时间,而不是移动字符串几次?
- 如何计算特定字母在字符串中出现的次数?(C++)
- 计算在同一位置至少包含一个常用字符的不同字符串对
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 使用标准库计算字符串中的十进制数
- 如何计算字符串中用户输入元素的出现次数?
- 如何在 C++ 中计算字符串的算术运算
- 计算字符串中子字符串的出现次数
- 用于计算字符串中元音的函数
- 当 NUL 字符被定义为字符串的一部分时,为什么 strlen() 不计算终止 NUL 字符的字节?
- 计算表达式字符串由 std::map 中的键组成
- 如何计算字符串 c++ 中的"xxx"数?
- 通过将文本文件读取为字符串/向量来计算加权/未加权 GPA
- 如何更有效地计算n个字符串之间的不匹配分数?
- 将字符串计算为 C++ 中的表达式
- 在C++中从字符串计算算术表达式
- 在字符串计算后添加空字符
- C++使用C字符串计算文件中的字符、单词、句子
- 不使用字符串计算数字中的数字