Skip to content

[C++] 在 string 字串中使用 find() 查找字串

Last Updated on 2021-10-22 by Clay

C++ 所提供的 STL 中的 string 模板,在處理字串方面非常方便。今天要紀錄,便是在 string 字串中,如何查找特定的文字、字串。

以下紀錄使用的函式分別為:

  • find()
  • find_first_of()
  • find_last_of()

find() 函式

find() 函式可以找的字串中是否包含特定的文字或字串,並回傳查找的文字索引(index)。

返回的查找結果為 size_t 型態,是無號整數型態unsigned integral type)。

#include <iostream>
#include <string>
using namespace std;

int main() {
    // Init
    string s = "Today is a nice day";
    string w1 = "nice";
    string w2 = "today";

    // npos
    printf("npos: %lu\n\n", s.npos);

    // find()
    // w1
    size_t found1 = s.find(w1);
    if (found1 != s.npos) {
        printf("found word \"%s\" at: %lu\n", w1.c_str(), found1);
    }
    else {
        printf("The word \"%s\" not found.\n", w1.c_str());
    }

    // w2
    size_t found2 = s.find(w2);
    if (found2 != s.npos) {
        printf("found word \"%s\" at: %lu\n", w2.c_str(), found2);
    }
    else {
        printf("The word \"%s\" not found.\n", w2.c_str());
    }
   

    return 0;
}


Output:

npos: 18446744073709551615

found word "nice" at: 11
The word "today" not found.


其中,若是返回的查找結果為 s.npos(即 18446744073709551615),則意味著並無匹配到查找字串。


find_first_of() 與 find_last_of()

正如函式名稱所示,find_first_of() 返回匹配到的第一個結果索引、find_last_of() 返回匹配到的最後一個結果索引。

#include <iostream>
#include <string>
using namespace std;

int main() {
    // Init
    string s = "Today is a nice day";
    string w = "day";

    // npos
    printf("s: %s\n\n", s.c_str());

    // find_first_of()
    size_t found1 = s.find_first_of(w);
    if (found1 != s.npos) {
        printf("found word \"%s\" at: %lu\n", w.c_str(), found1);
    }
    else {
        printf("The word \"%s\" not found.\n", w.c_str());
    }

    // find_last_of()
    size_t found2 = s.find_last_of(w);
    if (found2 != s.npos) {
        printf("found word \"%s\" at: %lu\n", w.c_str(), found2);
    }
    else {
        printf("The word \"%s\" not found.\n", w.c_str());
    }
   

    return 0;
}


Output:

s: Today is a nice day

found word "day" at: 2
found word "day" at: 18

References


Read More

Tags:

Leave a Reply取消回覆

Exit mobile version