天天看點

C++ 字元串查找函數

作者:睿智的海邊風浪

1. find

find函數用于在string中查找一個子串,傳回子串的首個字元所在的下标位置。如果查找失敗,則傳回string::npos。

string str = "hello world!";
string substr = "world";
size_t pos = str.find(substr);
if (pos != string::npos) {
    cout << "Found at position: " << pos << endl;
}           

2. rfind

rfind 函數與 find 函數類似,不同的是它從字元串的末尾開始查找子串。如果查找失敗,則傳回string::npos。

string str = "hello world!";
string substr = "l";
size_t pos = str.rfind(substr);
if (pos != string::npos) {
    cout << "Found at position: " << pos << endl;
}           

3. find_first_of

find_first_of函數用于查找字元串中第一個比對子串中的任意字元的位置,傳回子串的首個字元所在的下标位置。如果查找失敗,則傳回string::npos。

string str = "hello world!";
// 查找 'o' 或者 'w' 的第一個出現的位置。
string substr = "ow";	
size_t pos = str.find_first_of(substr);
if (pos != string::npos) {
    cout << "Found at position: " << pos << endl;
}           

4. find_last_of

find_last_of函數與find_first_of函數類似,不同的是它從字元串的末尾開始查找第一個比對子串中的任意字元的位置。如果查找失敗,則傳回string::npos。

string str = "hello world!";
string substr = "ow";
size_t pos = str.find_last_of(substr);
if (pos != string::npos) {
    cout << "Found at position: " << pos << endl;
}           

find_first_not_of()

find_first_not_of() 方法在字元串中查找第一個不屬于指定字元集的字元,并傳回該字元的位置。

size_t find_first_not_of (const string& str, size_t pos = 0) const noexcept;
size_t find_first_not_of (const char* s, size_t pos, size_t n) const;
size_t find_first_not_of (const char* s, size_t pos = 0) const;
size_t find_first_not_of (char c, size_t pos = 0) const noexcept;           

參數說明:

  • str:要查找的字元串。
  • s:要查找的字元數組。
  • n:查找字元數組的長度。
  • pos:查找起始位置。
  • c:要查找的字元。

函數傳回值:

  • 如果找到了指定字元集之外的字元,則傳回該字元在字元串中的位置。
  • 如果沒有找到符合條件的字元,則傳回string::npos。

find_last_not_of()

find_last_not_of() 方法在字元串中查找最後一個不屬于指定字元集的字元,并傳回該字元的位置。

size_t find_last_not_of (const string& str, size_t pos = npos) const noexcept;
size_t find_last_not_of (const char* s, size_t pos, size_t n) const;
size_t find_last_not_of (const char* s, size_t pos = npos) const;
size_t find_last_not_of (char c, size_t pos = npos) const noexcept;           

參數說明:

  • str:要查找的字元串。
  • s:要查找的字元數組。
  • n:查找字元數組的長度。
  • pos:查找結束位置。
  • c:要查找的字元。

函數傳回值:

  • 如果找到了指定字元集之外的字元,則傳回該字元在字元串中的位置。
  • 如果沒有找到符合條件的字元,則傳回string::npos。

繼續閱讀