Is there a reverse function for strstr

2020-02-11 18:50发布

I am trying to find a similar function to strstr that searches a substring starting from the end towards the beginning of the string.

标签: c++ c string
17条回答
我想做一个坏孩纸
2楼-- · 2020-02-11 19:07

You can use standard algorithm std::find_end for this purpose. For example

    char s[] = "What is the last word last";
    char t[] = "last";

    std::cout << std::find_end( s, s + sizeof( s ) - 1, t, t + sizeof( t ) -1 )
              << std::endl;
查看更多
Anthone
3楼-- · 2020-02-11 19:09

There isn't one in the standard C library. You may be able to find one on the web, or you may have to write your own.

查看更多
家丑人穷心不美
4楼-- · 2020-02-11 19:09

Long story short:

Nope - there is no function in the C-library that does what you need..

But as others have pointed out: It's not rocket-science to write such a function...

查看更多
爷、活的狠高调
5楼-- · 2020-02-11 19:14

Here is the most minimal simple implantation that I could come up with. Unlike other implementations of this function it avoids the initial strstr call that some other people like user3119703 had.

char * lastStrstr(const char * haystack,const char * needle){
    char*temp=haystack,*before=0;
    while(temp=strstr(temp,needle)) before=temp++;
    return before;
}
查看更多
三岁会撩人
6楼-- · 2020-02-11 19:16

If you can use C++, you can search strings like this:

std::string::iterator found=std::search(haystack.rbegin(), haystack.rend(), needle.rbegin(), needle.rend()).base();
// => yields haystack.begin() if not found, otherwise, an iterator past-the end of the occurence of needle
查看更多
登录 后发表回答