美文网首页
C++ string startsWith endsWit

C++ string startsWith endsWit

作者: book_02 | 来源:发表于2022-01-07 10:10 被阅读0次

cppstring本身是没有startsWithendsWith这些成员函数的,不像Java那样方便。

但是判断前缀和后缀的功能经常被用到,这两个功能也可以自己写,这里使用STL现有的函数来实现,是参考的网页大神的回复:

1. 代码汇总

先把实现代码汇总如下,后再详细解释:

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. starsWith 的功能替代

先把实现列出如下:

bool startsWith(const std::string& str, const std::string prefix) {
    return (str.rfind(prefix, 0) == 0);
}

string有个成员函数rfind,有原型如下:

size_t rfind (const string& str, size_t pos = npos) const;

当指定pos参数时,会忽略pos之后的结果位置,因此当设定0时,相当于搜索前缀了

When pos is specified, the search only includes sequences of characters that begin at or before position pos,   
ignoring any possible match beginning after pos.

例子如下:

#include <iostream>
#include <string>

int main(int argc, char* argv[])
{    
    std::string str("The sixth sick The sheik's sixth sheep's sick");

    if (startsWith(str, "The")) {
        std::cout << "startsWith" << std::endl;
    }       
    else {
        std::cout << "no specific prefix" << std::endl;
    }
    
    return 0;
}

3. endsWith 的功能替代

先把实现列出如下:

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

还是使用rfindrfind是找出最后一个出现的位置

Searches the string for the last occurrence of the sequence specified by its arguments.

当判断位置是(str.length() - suffix.length())时,便说明是后缀了

例子如下:

#include <iostream>
#include <string>

int main(int argc, char* argv[])
{    
    std::string str("The sixth sick The sheik's sixth sheep's sick");

    if (endsWith(str, "sick")) {
        std::cout << "endsWith" << std::endl;
    }
    else {
        std::cout << "no specific suffix" << std::endl;
    }
    
    return 0;
}

4. 参考

https://stackoverflow.com/questions/1878001/how-do-i-check-if-a-c-stdstring-starts-with-a-certain-string-and-convert-a

https://stackoverflow.com/questions/874134/find-out-if-string-ends-with-another-string-in-c

http://www.cplusplus.com/reference/string/string/rfind/

https://www.cplusplus.com/reference/string/string/find/

相关文章

网友评论

      本文标题:C++ string startsWith endsWit

      本文链接:https://www.haomeiwen.com/subject/zbcjcrtx.html