前言
C++的字符串的正向查找通常使用.find,那你知道如果倒着查吗?
一、倒查字符串的方法是什么?
通常正向查找字符串内第一次出现子串的位置时使用如下方法:
#正序查找
std::string zifuchuan = "use for test and test the effect";
std::string chazhao = "test";
int weizhi = zifuchuan.find(chazhao);
std::string zichuan = zifuzhuan.substr(weizhi+1,zifuchuan.length());
而倒着查目标第一次出现的位置就只需要将上述代码中的find()换成rfind()即可。
#倒序查找
std::string zifuchuan = "use for test and test the effect";
std::string chazhao = "test";
int weizhi = zifuchuan.rfind(chazhao);
std::string zichuan = zifuzhuan.substr(weizhi+1,zifuchuan.length());
二、代码结果分析
1.正序查找
从左到右第一次出现"test"的位置(存入weizhi中),获取此位置往右的内容作为子串(存入zichuan中)。
zichuan = "test and test the effect";
2.倒序查找
从右到左第一次出现"test"的位置(存入weizhi中),获取此位置往右的内容作为子串(存入zichuan中)。
zichuan = "test the effect";
总结
倒序查找的rfind和正序查找的find,得到的都是目标内容第一次出现的位置。
同时,要注意提取子串时位置(weizhi的值)要加一。