【贪玩巴斯】C++ tips——知识点:find()函数 & find_first_of()函数 & 类似Java中的indexOf()函数

欢迎关注我的微信公众号:
编程之蓁

ID:
bianchengzhizhen
及时分享算法、计算机科学以及游戏编程内容

本人CSDN博客主页:
https://blog.csdn.net/D16100?spm=1000.2115.3001.5343&type=blog
欢迎互相交流学习

类似于Java中的IndexOf函数:

这里介绍一下indexOf()的两种用法和实现功能:

1. indexOf(String str):

返回指定字符str在字符串中(方法调用者)第一次出现处的起始索引,如果此字符串中没有这样的字符,则返回 -1。

2.indexOf(String str, int index):

返回从 index 位置开始查找指定字符str在字符串中第一次出现处的起始索引,如果此字符串中没有这样的字符,则返回 -1。

C++中:

find() 函数

函数构造:

函数原型:
size_t find ( const string& str, size_t pos = 0 ) const;
size_t find ( const char* s, size_t pos, size_t n ) const;
size_t find ( const char* s, size_t pos = 0 ) const;
size_t find ( char c, size_t pos = 0 ) const;

参数说明:
pos 查找起始位置
n 待查找字符串的前n个字符

具体例子:

使用样例:
string str1(“tan wan ba si”);
string str2(“tan”);

上面定义出了两个字符串;

str1.find(str2);
// 从串str1中查找时str2,返回str2中首个字符在str1中的地址

str1.find(str2, 5);
// 从str1的第5个字符开始查找str2

str1.find(“ba”);
// 如果ba在str1中查找到,返回b在str1中的位置

str1.find(“a”);
// 查找字符o并返回地址

str1.find(“ba si”,2,2);
// 从str1中的第二个字符开始查找ba si的前两个字符

find_first_of()函数(该函数查找的是字符串中任意字符的位置)

函数构造

函数原型:

size_t find_first_of ( const string& str, size_t pos = 0 ) const;
size_t find_first_of ( const char* s, size_t pos, size_t n ) const;
size_t find_first_of ( const char* s, size_t pos = 0 ) const;
size_t find_first_of ( char c, size_t pos = 0 ) const;

pos 查找起始位置
n 待查找字符串的前n个字符

注意:
find_first_of 函数最容易出错的地方是和find函数搞混。它最大的区别就是如果在一个字符串str1中查找另一个字符串str2,如果str1中含有str2中的任何字符,则就会查找成功,而find则不同;

比如:

string str1(“I am change”);
string str2(“about”);

int k=str1.find_first_of(str2);
//k返回的值是about这5个字符中任何一个首次在str1中出现的位置;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贪玩巴斯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值