如何使用C/C++从字符串路径"/ user/desktop/abc/post /"中找到子字符串?我想检查该路径中是否存在"abc"文件夹.
路径是字符指针 char *ptr = "/user/desktop/abc/post/";
Luc*_*ore 36
使用std::string和find.
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)
注意不要意外地找到太短的子串(这是起始和结束斜杠的用途).
小智 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)
| 归档时间: |
|
| 查看次数: |
97635 次 |
| 最近记录: |