冰楓論壇

標題: [C++] 搜尋字串中是否存在特定字串 [打印本頁]

作者: whitefox    時間: 2023-6-27 23:35
標題: [C++] 搜尋字串中是否存在特定字串
本帖最後由 whitefox 於 2023-6-27 23:37 編輯


C風格搜尋法
  1. #include <iostream>
  2. #include <string>
  3. #include <cstring>
  4. using namespace std;
  5. int main()
  6. {
  7.     string a = "abcdefghi";
  8.     char*  b = "def";
  9.     char*  c = "123";

  10.     // 在 a 中搜尋 b -> 可找到的例子
  11.     if (strstr(a.c_str(), b) == NULL)
  12.         // 如果搜尋不到,輸出找不到
  13.         cout << "Not Found\n";
  14.     else
  15.         // 否則是已搜尋,輸出已找到
  16.         cout << "Found\n";

  17.     // 在 a 中搜尋 c -> 找不到的例子
  18.     if (strstr(a.c_str(), c) == NULL)
  19.         // 如果搜尋不到,輸出找不到
  20.         cout << "Not Found\n";
  21.     else
  22.         // 否則是已搜尋,輸出已找到
  23.         cout << "Found\n";
  24.     return 0;
  25. }
複製代碼
C++風格搜尋法(加入類別引用)
  1. #include <iostream>
  2. #include <string>

  3. using namespace std;
  4. int main()
  5. {
  6.     string a = "abcdefghi";
  7.     string b = "def";
  8.     string c = "123";
  9.     string::size_type idx;

  10.     // 在 a 中搜尋 b -> 可找到的例子
  11.     idx = a.find(b);
  12.     if (idx == string::npos )
  13.         // 如果搜尋不到,輸出找不到
  14.         cout << "Not Found\n";
  15.     else
  16.         // 否則是已搜尋,輸出已找到
  17.         cout << "Found\n";

  18.     // 在 a 中搜尋 c -> 找不到的例子
  19.     idx = a.find(c);
  20.     if (idx == string::npos )
  21.         // 如果搜尋不到,輸出找不到
  22.         cout << "Not Found\n";
  23.     else
  24.         // 否則是已搜尋,輸出已找到
  25.         cout << "Found\n";
  26.     return 0;
  27. }
複製代碼

作者: odasm    時間: 2025-12-10 05:14
「貨出得去,人進得來,高雄發大財」




歡迎光臨 冰楓論壇 (https://bingfong.com/) Powered by 冰楓