String類find函數的瞭解(string::npos的含義)

問題

現有兩個字符串a和b, 想判斷a字符串是否包含b字符串,該如何設計程序?LeetCode上有道題會用到。

思路

此處就需要用到string庫中的find函數與npos參數。

先說說string::npos參數:
npos 是一個常數,用來表示不存在的位置,類型一般是std::container_type::size_type 許多容器都提供這個東西;取值由實現決定,一般是-1,這樣做,就不會存在移植的問題。

再來說說find函數:
find函數的返回值是整數,假如字符串存在包含關係,其返回值必定不等於npos,但如果字符串不存在包含關係;那麼返回值就一定是npos,所以很容易想到用if判斷語句來實現。

簡單而言:如果存在包含關係find函數返回的就是主串與子串相匹配的下標,如果不存在包含關係就返回。

npos(一個常數,表示不存在)(s.find(“abcdefg”)==string::npos)

 if (a.find(b) != string::npos)
 {
     cout << "a contains b" << endl;
 }
 else
 {
     cout << "a does not contain b" << endl;
 }
 # include <iostream>
 # include <string>
 using namespace std;
  
 int main() 
 {
     int number;
     cin >> number;
     while (number--) 
     {
         string a, b;
         cin >> a >> b;
         int pos = a.find(b);
         if (pos == string::npos) 
         {
             cout << "no" << endl;
         }
         else 
         {
             cout << "yes" << endl;
         }
     }
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章