——String类find函数深入了解一下(string::npos的含义)


问题:有两个字符串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 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM