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;
}
}