鱼C论坛

 找回密码
 立即注册
查看: 2210|回复: 3

[已解决]如何查找一个字符串里面相同内容出现的次数

[复制链接]
发表于 2023-10-12 15:12:15 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
使用find()函数
最佳答案
2023-10-12 15:13:21
你可以使用C++的std::string类提供的find()函数来查找一个字符串中相同内容出现的次数。以下是一个示例代码:
  1. #include <iostream>
  2. #include <string>
  3. int countOccurrences(const std::string& str, const std::string& search) {
  4.     int count = 0;
  5.     size_t pos = 0;
  6.    
  7.     while ((pos = str.find(search, pos)) != std::string::npos) {
  8.         count++;
  9.         pos += search.length();
  10.     }
  11.    
  12.     return count;
  13. }
  14. int main() {
  15.     std::string str;
  16.     std::string search;
  17.    
  18.     std::cout << "Enter a string: ";
  19.     std::getline(std::cin, str);
  20.    
  21.     std::cout << "Enter a search term: ";
  22.     std::getline(std::cin, search);
  23.    
  24.     int occurrences = countOccurrences(str, search);
  25.    
  26.     std::cout << "Number of occurrences: " << occurrences << std::endl;
  27.    
  28.     return 0;
  29. }
复制代码

这段代码定义了一个countOccurrences()函数,该函数接受两个参数:原始字符串str和要搜索的字符串search。它使用std::stringfind()函数在str中循环查找search出现的位置,并使用一个计数器count记录找到的次数。

在主函数main()中,用户可以从键盘输入一个字符串和一个搜索词,然后调用countOccurrences()函数来获取出现的次数,并输出结果。

注意,在该示例代码中,使用std::getline()函数来获取包含空格的输入字符串,以避免因为空格而截断输入。

希望这个示例对你有所帮助!

球一个最佳答案谢谢啦!这对我非常重要!
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-9-22 04:06

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表