C++填坑之std::string::find_first_of

在C++中会有STL库相关的操作,其中std::string::find_first_of  就是其中之一。

其返回值为 size_t 类型。size_t is an unsigned integral type

我们再看一下其返回值:

1、查找的字符所在的位置。

2、如果没有相匹配的字符,则返回 string::npos

示例如下:

示例来自:http://www.cplusplus.com/reference/string/string/find_first_of/

// string::find_first_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t

int main ()
{
  std::string str ("Please, replace the vowels in this sentence by asterisks.");
  std::size_t found = str.find_first_of("aeiou");
  while (found!=std::string::npos)
  {
    str[found]='*';
    found=str.find_first_of("aeiou",found+1);
  }

  std::cout << str << '\n';

  return 0;
}
以上使用没有问题。问题在于接过前辈的代码时

使用了 if(found > 0)的判断条件。当能找到一个字符时,这个条件自然满足。

当找不到查找的字符时,返回的值为 -1 ,此时size_t为无符号数,就存在溢出的情况,这个判断条件依然存在。所以这里应该使用的判断条件应该和npos相比较。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值