1.代码汇总
代码的判断使用了rfind函数,该函数的作用将在后面具体解释
bool startsWith(const std::string& str, const std::string prefix) {
return (str.rfind(prefix, 0) == 0);
}
bool endsWith(const std::string& str, const std::string suffix) {
if (suffix.length() > str.length()) { return false; }
return (str.rfind(suffix) == (str.length() - suffix.length()));
}
2.判断前缀
前缀的判断代码如下
bool startsWith(const std::string& str, const std::string prefix) {
return (str.rfind(prefix, 0) == 0);
}
其中rfind函数是string的成员函数之一,原型如下
size_t rfind (const string& str, size_t pos = npos) const;
rfind函数的作用是查找模式串str在当前字符串中最后一次出现的位置,pos代表从第pos个位置开始逆向查找,但是匹配是正向匹配的
string中还有一个成员函数时find函数,原型如下
size_t find(const string str, size_t pos = npos) const;
find函数的作用于rfind类似,但是是正向查找模式串str出现的第一个位置,pos代表从0开始到pos位置结束中正向查找,并且也是正向匹配
其实find函数也可以完成同样的判断,只需要把判断前缀代码中的rfind改成find即可
3.判断后缀
后缀的判断代码如下:
bool endsWith(const std::string& str, const std::string suffix) {
if (suffix.length() > str.length()) { return false; }
return (str.rfind(suffix) == (str.length() - suffix.length()));
}
后缀的判断方式几乎与前缀相同,首先判断目标字符串与当前字符串的长度,目标字符串大于当前字符串则返回错误,然后判断目标字符串在当前字符串最后一次出现的位置