冰楓論壇
標題:
[C++] 搜尋字串中是否存在特定字串
[打印本頁]
作者:
whitefox
時間:
2023-6-27 23:35
標題:
[C++] 搜尋字串中是否存在特定字串
本帖最後由 whitefox 於 2023-6-27 23:37 編輯
C風格搜尋法
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string a = "abcdefghi";
char* b = "def";
char* c = "123";
// 在 a 中搜尋 b -> 可找到的例子
if (strstr(a.c_str(), b) == NULL)
// 如果搜尋不到,輸出找不到
cout << "Not Found\n";
else
// 否則是已搜尋,輸出已找到
cout << "Found\n";
// 在 a 中搜尋 c -> 找不到的例子
if (strstr(a.c_str(), c) == NULL)
// 如果搜尋不到,輸出找不到
cout << "Not Found\n";
else
// 否則是已搜尋,輸出已找到
cout << "Found\n";
return 0;
}
複製代碼
C++風格搜尋法(加入類別引用)
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a = "abcdefghi";
string b = "def";
string c = "123";
string::size_type idx;
// 在 a 中搜尋 b -> 可找到的例子
idx = a.find(b);
if (idx == string::npos )
// 如果搜尋不到,輸出找不到
cout << "Not Found\n";
else
// 否則是已搜尋,輸出已找到
cout << "Found\n";
// 在 a 中搜尋 c -> 找不到的例子
idx = a.find(c);
if (idx == string::npos )
// 如果搜尋不到,輸出找不到
cout << "Not Found\n";
else
// 否則是已搜尋,輸出已找到
cout << "Found\n";
return 0;
}
複製代碼
作者:
odasm
時間:
2025-12-10 05:14
「貨出得去,人進得來,高雄發大財」
歡迎光臨 冰楓論壇 (https://bingfong.com/)
Powered by 冰楓