要求输入一段文字,程序可以统计出某一字符串在这段文字中出现的次数以及位置。
参考GPT
#include <iostream>
#include <string>
using namespace std;
int main() {
// 从键盘输入原始文本和待查找的字符串
string text, word;
cout << "请输入一段文本:";
getline(cin, text);
cout << "请输入待查找的字符串:";
getline(cin, word);
// 统计字符串出现次数和位置
int count = 0;
size_t pos = text.find(word);
while (pos != string::npos) {
count++;
cout << "第 " << count << " 个 \"" << word << "\" 在文本中出现的位置是: " << pos << endl;
pos = text.find(word, pos + 1);
}
// 输出结果
cout << "\"" << word << "\" 在文本中出现了 " << count << " 次。" << endl;
return 0;
}
程序运行时,会提示用户输入一段文本和待查找的字符串。然后程序会使用string::find()
函数在文本中查找待查找的字符串,并统计其出现次数和位置。最后程序会输出结果,显示待查找的字符串在原始文本中出现的次数和位置。
需要注意的是,string::find()
函数会返回第一个匹配子串的位置,如果没有找到则返回string::npos
。因此,在找到第一个匹配子串的位置之后,需要通过第二个参数指定查找的开始位置,以便继续查找下一个匹配子串。