我正在尝试将 char * 与 a 与 std::string 进行比较
const char *s = "0@s072116\tblah\tblah\blah";
std::string id = "072116";
我需要比较这两个,基本上是在第一个\t 之前和左边的前 3 个字符之后。 id 的宽度可以变化。 :(
我不太擅长 C++。有什么想法吗??
谢谢
最佳答案
您可以按如下方式进行:
#include <iostream>
#include <string>
using namespace std;
...
int main() {
const char *s = "0@s072116\tblah\tblah\blah";
string ss = s;
string id = "072116";
int found = ss.find(id);
cout << "found is: " << found;
}
如果id
是ss
中的一个子串,那么found
就是id
第一次出现的位置> 在 ss
中。
如果 id
不是 ss
中的子串,则 found
将为负数。
More examples在 find
上。
警告:
上面的代码是基于假设你的意思“......基本上在第一个\t 之前和左边的前 3 个字符之后......” 作为指出位置的一种方式在此特定示例中将匹配子字符串。
相反,如果它是所有实例都必须满足的要求(即 const char *s = "0@s\tblah\tblah\blah072116"
不应匹配),则提供的代码示例是不够的。
关于C++ 比较 const char* 和 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13519412/