如何从字符串中查找子字符串?

Cra*_*der 18 c c++

如何使用C/C++从字符串路径"/ user/desktop/abc/post /"中找到子字符串?我想检查该路径中是否存在"abc"文件夹.

路径是字符指针 char *ptr = "/user/desktop/abc/post/";

Luc*_*ore 36

使用std::stringfind.

std::string str = "/user/desktop/abc/post/";
bool exists = str.find("/abc/") != std::string::npos;
Run Code Online (Sandbox Code Playgroud)


unw*_*ind 17

在C中,使用strstr()标准库函数:

const char *str = "/user/desktop/abc/post/";
const int exists = strstr(str, "/abc/") != NULL;
Run Code Online (Sandbox Code Playgroud)

注意不要意外地找到太短的子串(这是起始和结束斜杠的用途).

  • 嗯..如果这是路径的最后一部分怎么办? (7认同)

小智 11

使用std::stringfind方法的示例:

#include <iostream>
#include <string>

int main (){
    std::string str ("There are two needles in this haystack with needles.");
    std::string str2 ("needle");

    size_t found = str.find(str2);
    if(found!=std::string::npos){ 
        std::cout << "first 'needle' found at: " << found << '\n';
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果:

first 'needle' found at: 14.
Run Code Online (Sandbox Code Playgroud)