C++ find,find_first_of,find_last_of

1. size_t find (const string& str, size_t pos = 0)#

str.find(str1)

说明:从pos(默认是是0,即从头开始查找)开始查找,找到第一个和str1相匹配的子串,返回该子串的起始索引位置;如果没有找到则返回string::npos
参考:find函数:http://www.cplusplus.com/reference/string/string/find/

2. size_t find_first_of (const string& str, size_t pos = 0)#

str.find_first_of(str1)

说明:从pos(默认是是0,即从头开始查找)开始查找,找到第一个和str1相匹配的子串,返回该子串的起始索引位置;如果没有找到则返回string::npos
参考:find_first_of函数:http://www.cplusplus.com/reference/string/string/find_first_of/

3.size_t find_last_of (const string& str, size_t pos = npos)#

str.find_last_of(str1)

说明:从npos(默认是字符串最后一个,即从后向前查找)开始查找,找到第一个和str1相匹配的子串,返回该子串的最后一个字符的索引位置;如果没有找到则返回string::npos
参考: find_last_of函数:http://www.cplusplus.com/reference/string/string/find_last_of/

小编在编写超市购物管理的时候遇到的问题。小编没有用数据库,用的读写文本文件,所以避免不了自己设定索引查找规则。小编针对字符串选用了string中的find。

下面是部分代码块:
大致功能是,按行遍历文本文件,直到某行含有content的内容。

while (getline(in, tempStr))
	{
		cout << tempStr << endl;
		i++;
		if (tempStr.find(content))
		{
			in.close();
			return i;
		}
	}

小编发现,这个代码每次的返回值都是1.于是查找官方文档:

Return Value
The position of the first character of the first match.
If no matches were found, the function returns string::npos.

size_t is an unsigned integral type (the same as member type string::size_type).

显示,如果匹配的没有找到,则返回string::npos,这个在if判断语句中也是按True处理的。

修改方法:

while (getline(in, tempStr))
	{
		cout << tempStr << endl;
		i++;
		if (tempStr.find(content)!=std::string::npos)
		{
			in.close();
			return i;
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值