C++中string查找子串技巧

发布时间:2024-10-09 13:37:19 作者:小樊
来源:亿速云 阅读:78

在 C++ 中,可以使用 std::string 类的成员函数 find() 来查找子串。以下是一些使用技巧:

  1. 查找子串的位置:使用 find() 函数可以查找子串在字符串中的位置。如果找到,则返回子串第一次出现的位置的索引;否则返回 std::string::npos。例如:

    std::string str = "hello world";
    std::string sub = "world";
    size_t pos = str.find(sub);
    if (pos != std::string::npos) {
        std::cout << "子串的位置为:" << pos << std::endl;
    } else {
        std::cout << "未找到子串" << std::endl;
    }
    
  2. 查找子串的所有位置:如果要查找子串在字符串中的所有位置,可以使用循环调用 find() 函数。例如:

    std::string str = "hello world, world!";
    std::string sub = "world";
    size_t pos = str.find(sub);
    while (pos != std::string::npos) {
        std::cout << "子串的位置为:" << pos << std::endl;
        pos = str.find(sub, pos + 1);
    }
    
  3. 查找子串时忽略大小写:如果要查找的子串和目标字符串的大小写不同,可以使用 std::string 类的 lower()upper() 函数将它们转换为小写或大写,然后再进行查找。例如:

    std::string str = "Hello World!";
    std::string sub = "WORLD";
    std::transform(str.begin(), str.end(), str.begin(), ::tolower);
    std::transform(sub.begin(), sub.end(), sub.begin(), ::tolower);
    size_t pos = str.find(sub);
    if (pos != std::string::npos) {
        std::cout << "子串的位置为:" << pos << std::endl;
    } else {
        std::cout << "未找到子串" << std::endl;
    }
    
  4. 使用正则表达式进行查找:std::string 类还提供了 regex 类型的成员函数 find(),可以使用正则表达式进行查找。例如:

    #include <regex>
    
    std::string str = "hello 123 world 456";
    std::regex re("\\d+");
    std::smatch match;
    while (std::regex_search(str, match, re)) {
        std::cout << "匹配到的数字为:" << match[0] << std::endl;
        str = match.suffix().str();
    }
    
推荐阅读:
  1. C++中如何实现链表的排序算法
  2. C++如何实现拓扑排序算法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:字符串拼接C++最优方法

下一篇:string库替换字符如何实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》