首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

string string:在一个字符串中获取多个in,并将它们返回给vector

答案: 在C++中,我们可以使用string类和vector类来实现在一个字符串中获取多个in,并将它们返回给vector的功能。

首先,我们需要使用string类的find函数来查找字符串中的子串。find函数会返回子串在字符串中的位置,如果找不到则返回string::npos。

然后,我们可以使用一个循环来重复查找字符串中的子串。每次找到子串后,我们可以将其位置保存到一个vector中。

下面是一个示例代码:

代码语言:txt
复制
#include <iostream>
#include <string>
#include <vector>

std::vector<size_t> findOccurrences(const std::string& str, const std::string& subStr) {
    std::vector<size_t> occurrences;
    size_t pos = 0;
    
    while ((pos = str.find(subStr, pos)) != std::string::npos) {
        occurrences.push_back(pos);
        pos += subStr.length();
    }
    
    return occurrences;
}

int main() {
    std::string str = "This is a string containing multiple 'in' occurrences";
    std::string subStr = "in";
    
    std::vector<size_t> occurrences = findOccurrences(str, subStr);
    
    for (size_t i = 0; i < occurrences.size(); ++i) {
        std::cout << "Occurrence " << i + 1 << " found at position " << occurrences[i] << std::endl;
    }
    
    return 0;
}

在上面的代码中,我们定义了一个名为findOccurrences的函数,它接受两个参数:一个是要搜索的字符串str,另一个是要查找的子串subStr。函数返回一个vector,其中包含了所有子串在字符串中的位置。

在主函数中,我们定义了一个示例字符串str和要查找的子串subStr。然后,我们调用findOccurrences函数来获取所有子串的位置,并将结果保存到occurrences向量中。最后,我们使用循环打印出每个子串在字符串中的位置。

这个功能在实际开发中非常常见,例如在文本处理、日志分析、字符串匹配等场景中都会用到。

腾讯云相关产品和产品介绍链接地址:

  • 腾讯云CVM(云服务器):https://cloud.tencent.com/product/cvm
  • 腾讯云COS(对象存储):https://cloud.tencent.com/product/cos
  • 腾讯云VPC(私有网络):https://cloud.tencent.com/product/vpc
  • 腾讯云CDN(内容分发网络):https://cloud.tencent.com/product/cdn
  • 腾讯云SCF(云函数):https://cloud.tencent.com/product/scf
  • 腾讯云CKafka(消息队列 CKafka):https://cloud.tencent.com/product/ckafka
  • 腾讯云CDB(云数据库 MySQL):https://cloud.tencent.com/product/cdb
  • 腾讯云SSL证书:https://cloud.tencent.com/product/ssl
  • 腾讯云DDoS防护:https://cloud.tencent.com/product/ddos
  • 腾讯云WAF(Web应用防火墙):https://cloud.tencent.com/product/waf
  • 腾讯云视频处理:https://cloud.tencent.com/product/vod
  • 腾讯云人脸识别:https://cloud.tencent.com/product/faceid
  • 腾讯云物联网通信:https://cloud.tencent.com/product/iotexplorer
  • 腾讯云区块链服务:https://cloud.tencent.com/product/tbaas
  • 腾讯云游戏多媒体引擎:https://cloud.tencent.com/product/gme
  • 腾讯云元宇宙:https://cloud.tencent.com/product/tencent-realtime-rendering
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

6分9秒

054.go创建error的四种方式

3分59秒

基于深度强化学习的机器人在多行人环境中的避障实验

领券