溫馨提示×

如何在c++中實現字符串的子串查找

c++
小樊
166
2024-09-25 07:36:16
欄目: 編程語言

在 C++ 中,可以使用 std::string 類的成員函數 find() 來實現字符串的子串查找。

find() 函數的原型如下:

size_t find(const std::string& str, size_t pos = 0) const;

其中,str 是要查找的子串,pos 是可選參數,表示從哪個位置開始查找。如果省略該參數,則從字符串的開頭開始查找。

函數返回子串在字符串中第一次出現的位置,如果沒有找到則返回 std::string::npos。

下面是一個簡單的示例代碼:

#include <iostream>
#include <string>

int main() {
    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;
    }

    return 0;
}

輸出結果為:

子串的起始位置為:6

注意,find() 函數是區分大小寫的。如果要執行不區分大小寫的查找,可以在查找之前將字符串轉換為小寫(或大寫):

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;
}

輸出結果為:

子串的起始位置為:6

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女