溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C++中string查找子串技巧

發(fā)布時間:2024-10-09 13:37:19 來源:億速云 閱讀:78 作者:小樊 欄目:編程語言

在 C++ 中,可以使用 std::string 類的成員函數(shù) find() 來查找子串。以下是一些使用技巧:

  1. 查找子串的位置:使用 find() 函數(shù)可以查找子串在字符串中的位置。如果找到,則返回子串第一次出現(xiàn)的位置的索引;否則返回 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. 查找子串的所有位置:如果要查找子串在字符串中的所有位置,可以使用循環(huán)調用 find() 函數(shù)。例如:

    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() 函數(shù)將它們轉換為小寫或大寫,然后再進行查找。例如:

    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 類型的成員函數(shù) 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 << "匹配到的數(shù)字為:" << match[0] << std::endl;
        str = match.suffix().str();
    }
    
向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

c++
AI