問題:有兩個字符串a、b, 現想判斷a字符串是否包含b字符串,該如何設計程序?
思路:此處需要用到string庫中的find函數與npos參數。
先說說string::npos參數:
npos 是一個常數,用來表示不存在的位置,類型一般是std::container_type::size_type 許多容器都提供這個東西。
取值由實現決定,一般是-1,這樣做,就不會存在移植的問題了。
再來說說find函數:
find函數的返回值是整數,假如字符串存在包含關系,其返回值必定不等於npos,但如果字符串不存在包含關系,
那么返回值就一定是npos。所以不難想到用if判斷語句來實現!
簡單而言:如果存在包含關系find函數返回的就是主串與子串相匹配的下標,如果不存在包含關系就返回npos(一個常數,表示不存在)(s.find("abcdefg")==string::npos)
1 if (a.find(b) != string::npos){ 2 cout << "a contains b" << endl; 3 } 4 else{ 5 cout << "a does not contain b" << endl; 6 }
現完整如下:
1 # include <iostream> 2 # include <string> 3 using namespace std; 4 5 int main() { 6 int number; 7 cin >> number; 8 while (number--) { 9 string a, b; 10 cin >> a >> b; 11 int pos = a.find(b); 12 if (pos == string::npos) { 13 cout << "NO" << endl; 14 } 15 else { 16 cout << "YES" << endl; 17 } 18 } 19 }