0

我正在尝试将 char * 与 a 与 std::string 进行比较

const char *s = "0@s072116\tblah\tblah\blah";
std::string id = "072116";

我需要比较这两个,基本上在第一个 \t 之前和左边的前 3 个字符之后。id 的宽度可以变化。:(

我不太擅长 C++。有任何想法吗??

谢谢

4

2 回答 2

4

你可以这样做:

#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是 in 的子字符串ssfound则将是 in 的第一次出现的id位置ss

如果id不是 中的子字符串ss,那么found将是一个负数。

find更多示例

警告:

上面的代码基于假设您的意思是“......基本上在第一个 \t 之前和左边的前 3 个字符之后......”作为指出在这个特定示例中子字符串匹配位置的一种方式。

相反,如果它是所有实例都必须满足的要求(即const char *s = "0@s\tblah\tblah\blah072116"不应匹配),那么提供的代码示例是不够的。

于 2012-11-22T20:14:10.863 回答
0
const char *position = std::search(s, s + std::strlen(s), id.begin(), id.end());
if (*position == '\0')
    std::cout << "Not found\n";
else
    std::cout << "Found at offset " << (position - s) << '\n';
于 2012-11-22T21:19:41.690 回答