你可以使用C++的
std::string类提供的
find()函数来查找一个字符串中相同内容出现的次数。以下是一个示例代码:
- #include <iostream>
- #include <string>
- int countOccurrences(const std::string& str, const std::string& search) {
- int count = 0;
- size_t pos = 0;
-
- while ((pos = str.find(search, pos)) != std::string::npos) {
- count++;
- pos += search.length();
- }
-
- return count;
- }
- int main() {
- std::string str;
- std::string search;
-
- std::cout << "Enter a string: ";
- std::getline(std::cin, str);
-
- std::cout << "Enter a search term: ";
- std::getline(std::cin, search);
-
- int occurrences = countOccurrences(str, search);
-
- std::cout << "Number of occurrences: " << occurrences << std::endl;
-
- return 0;
- }
复制代码
这段代码定义了一个
countOccurrences()函数,该函数接受两个参数:原始字符串
str和要搜索的字符串
search。它使用
std::string的
find()函数在
str中循环查找
search出现的位置,并使用一个计数器
count记录找到的次数。
在主函数
main()中,用户可以从键盘输入一个字符串和一个搜索词,然后调用
countOccurrences()函数来获取出现的次数,并输出结果。
注意,在该示例代码中,使用
std::getline()函数来获取包含空格的输入字符串,以避免因为空格而截断输入。
希望这个示例对你有所帮助!
球一个最佳答案谢谢啦!这对我非常重要!

