在c++ 中使用 string find()

最近在学习C++编程,感觉很多东西经常使用到,但是每次查阅相关函数之后下次使用时还是不太记得,现在就对一些经常使用的string函数进行记录,以便自己在日后的查阅使用,近一步学习

std::string::find

查找字符串中的子串,如果查找到就返回子串第一次出现的位置pos,如果没有查找到就返回string::npos,表示已经查找到字符串长度的最大值,没有这个字符串。同时在查找字符串之后,一般使用判断语句和判断是不是string::npos,表示能否查找相应字符子串,

如:

string str ("There are two needles in this haystack with needles.");
string str2 ("needle");
 std::size_t found = str.find(str2);//可以使用命名空间
  if (found!=std::string::npos)
    std::cout << "first 'needle' found at: " << found << '\n';
 found=str.find('.');
  if (found!=std::string::npos)
    std::cout << "Period found at: " << found << '\n';

  // let's replace the first needle:
  str.replace(str.find(str2),str2.length(),"preposition");//替换字符串
  std::cout << str << '\n';



Maximum value for size_t
npos is a static member constant value with the greatest possible value for an element of type size_t.

This value, when used as the value for a len (or sublen) parameter in string's member functions, means "until the end of the string".

As a return value, it is usually used to indicate no matches.

This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值