谷动谷力

 找回密码
 立即注册
查看: 373|回复: 0
打印 上一主题 下一主题
收起左侧

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

[复制链接]
跳转到指定楼层
楼主
发表于 2023-10-11 16:06:53 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
C++: 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判断语句来实现!
  1. if (a.find(b) != string::npos) {

  2.     cout << "Yes!" << endl;

  3. } else {

  4.     cout << "No!" << endl;

  5. }
复制代码


现完整代码如下:
  1. # include <iostream>
  2. # include <string>

  3. using namespace std;

  4. int main(void) {
  5.     int number;
  6.     cin >> number;

  7.     while (number--) {

  8.         string a, b;
  9.         cin >> a >> b;

  10.         int pos = a.find(b);

  11.         if (pos == string::npos) {
  12.             cout << "NO" << endl;
  13.         } else {
  14.             cout << "YES" << endl;
  15.         }
  16.     }

  17.     return 0;

  18. }
复制代码



+12

最近谁赞过

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|深圳市光明谷科技有限公司|光明谷商城|Sunshine Silicon Corpporation ( 粤ICP备14060730号|Sitemap

GMT+8, 2024-4-29 03:27 , Processed in 0.080342 second(s), 42 queries .

Powered by Discuz! X3.2 Licensed

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表