C++ std::string::find 搜尋字串用法與範例

本篇介紹 C/C++ std::string::find 搜尋字串的用法與範例,

要使用 std::string::find 的話,需要引入的標頭檔: <string>

C++ std::string::find 搜尋字串使用範例

以下為 std::string::find 搜尋字串的範例,如果有找到的話會回傳找到的位置,如果沒有找到會回傳 string::npos,以下例子示範有找到跟沒找到的情況,並且有找到的話把位置印出來,

std-string-find.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// g++ std-string-find.cpp -o a.out
#include <iostream>
#include <string>

int main() {
std::string str = "Hello World";
std::string str2("World");

std::size_t found = str.find(str2);
if (found != std::string::npos) {
std::cout << "found at " << found << "\n";
}

found = str.find("Wo");
if (found != std::string::npos) {
std::cout << "found at " << found << "\n";
}

found = str.find("lo");
if (found != std::string::npos) {
std::cout << "found at " << found << "\n";
}

found = str.find("Hx");
if (found != std::string::npos) {
std::cout << "4 found\n";
} else {
std::cout << "not found\n";
}

return 0;
}

輸出如下,

1
2
3
4
found at 6
found at 6
found at 3
not found

C++ std::string::rfind 由後往前搜尋字串

如果要由後往前搜尋字串的話可以改使用 std::string::rfind,rfind 字面上的意思就是從字串右邊向左搜尋,在某些情況下可以增進搜尋效率,例如我要在絕對路徑中擷取檔案名稱或目錄名稱時,通常會先去找絕對路徑中最右邊的 '/' 字元,再從找到的 '/' 字元起始位置之後取出子字串。另外補充一下 linux / macOS 的路徑分隔字元為 /,Windows 的路徑分隔字元為 \,在程式裡要用兩個反斜線 \\ 代表 \

std-string-rfind.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// g++ std-string-rfind.cpp -o a.out
#include <iostream>
#include <string>

int main() {
std::string str = "/home/shengyu/Desktop";
std::size_t found = str.rfind("/");
if (found != std::string::npos) {
std::cout << "found at " << found << "\n";
std::cout << str.substr(found+1) << "\n";
} else {
std::cout << "not found\n";
}

return 0;
}

輸出如下,找到最右邊的 / 字元的起始位置在 13,並且用 string::substr 擷取出子字串,

1
2
found at 13
Desktop

以上就是 C++ std::string::find 搜尋字串用法與範例介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!

其他參考
string::find - C++ Reference
https://www.cplusplus.com/reference/string/string/find/

其它相關文章推薦
C/C++ 新手入門教學懶人包
std::string 用法與範例
C++ virtual 的兩種用法
C/C++ 字串反轉 reverse
C/C++ call by value傳值, call by pointer傳址, call by reference傳參考 的差別
C++ 類別樣板 class template
std::sort 用法與範例
std::find 用法與範例
std::queue 用法與範例
std::map 用法與範例