今日小技巧巩固记录:
rfind() 函数用法一句话总结:从后向前查找字符或者子字符串第一次出现的位置。
find()函数是从前往后查找。
举个栗子:rfind()
string path = "012/456789/2021-01-18"; //待操作的字符串
int pos = path.rfind('/'); // rfind(),从后向前找到'/'第一次出现的位置
cout << "pos is :" << pos << endl; // 打印‘/’的位置
if (pos != string::npos)
{
string path_2 = path.substr(pos + 1); // 从下一个位置开始截取
cout << path_2.c_str() << endl; // 打印日期
}
输出:
pos is :10
2021-01-18
说明字符 ‘/’最后一次出现在字符串 “012/456789/2021-01-18” 的第十位,且打印最后一个’/'后面的所有字串。
注意上下对比
再举个栗子:find()
string path = "012/456789/2021-01-18";
int pos = path.find('/'); // find(),从前向后找到'/'的位置
cout << "pos is :" << pos << endl; // 打印‘/’的位置
if (pos != string::npos)
{
string path_2 = path.substr(pos + 1); // 从下一个位置开始截取
cout << path_2.c_str() << endl; // 打印日期
}
输出:
pos is :3
456789/2021-01-18
说明字符 ‘/’第一次出现在字符串 “012/456789/2021-01-18” 的第3位,且打印第一个’/'后面的所有字串。
结束:
分享也是自己对问题再次加深理解的方式,可能不全面,但绝对有用,后面将不断完善~