Today’s tips to consolidate records:
A one-sentence summary of rfind() function usage: Find the first occurrence of a character or substring from back to front.
The find() function searches from front to back.
Give a chestnut: 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; // 打印日期
}
Output:
pos is :10
2021-01-18
Explain that the character'/' last appeared in the tenth position of the string "012/456789/2021-01-18", and print all the strings after the last'/'.
Pay attention to the top and bottom contrast
Give another chestnut: 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; // 打印日期
}
Output:
pos is :3
456789/2021-01-18
Explain that the character'/' appears in the 3rd position of the string "012/456789/2021-01-18" for the first time, and all the strings after the first'/' are printed.
End:
Sharing is also a way to deepen your understanding of the problem again. It may not be comprehensive, but it is definitely useful and will continue to be improved later~