C++: string 中find函数的用法以及string::npos的含义

C++: string 中find函数的用法以及string::npos的含义

标签:C++ string find函数 npos 字符串包含

by 小威威


问题:有两个字符串a、b, 现想判断a字符串是否包含b字符串,该如何设计程序?

思路:此处需要用到string库中的find函数npos参数

先说说string::npos参数
npos 是一个常数,用来表示不存在的位置,类型一般是std::container_type::size_type 许多容器都提供这个东西。取值由实现决定,一般是-1,这样做,就不会存在移植的问题了。
再来说说find函数
find函数的返回值是整数,假如字符串存在包含关系,其返回值必定不等于npos,但如果字符串不存在包含关系,那么返回值就一定是npos。所以不难想到用if判断语句来实现!

if (a.find(b) != string::npos) {
    cout << "Yes!" << endl;
} else {
    cout << "No!" << endl;
}
    
    
  • 1
  • 2
  • 3
  • 4
  • 5

现完整代码如下:

# include <iostream>
# include <string>

using namespace std;

int main(void) {
    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;
        }
    }
    return 0;
}

    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!


        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/markdown_views-ea0013b516.css">
            </div>

C++: string 中find函数的用法以及string::npos的含义

标签:C++ string find函数 npos 字符串包含

by 小威威


问题:有两个字符串a、b, 现想判断a字符串是否包含b字符串,该如何设计程序?

思路:此处需要用到string库中的find函数npos参数

先说说string::npos参数
npos 是一个常数,用来表示不存在的位置,类型一般是std::container_type::size_type 许多容器都提供这个东西。取值由实现决定,一般是-1,这样做,就不会存在移植的问题了。
再来说说find函数
find函数的返回值是整数,假如字符串存在包含关系,其返回值必定不等于npos,但如果字符串不存在包含关系,那么返回值就一定是npos。所以不难想到用if判断语句来实现!

if (a.find(b) != string::npos) {
    cout << "Yes!" << endl;
} else {
    cout << "No!" << endl;
}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5

现完整代码如下:

# include <iostream>
# include <string>

using namespace std;

int main(void) {
    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;
        }
    }
    return 0;
}

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!


        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/markdown_views-ea0013b516.css">
            </div>

猜你喜欢

转载自blog.csdn.net/breakpoints_/article/details/81214949