如何提取C 中的字符/字符串之间的字符串

How do you extract a string that is in between a char/string in C++?

本文关键字:字符串 之间 字符 何提取 提取      更新时间:2023-10-16

假设我有一个简单的字符串:

string example = "phone number: XXXXXXX,"

其中x是给我的随机值,因此它们总是不同的。如何仅提取X? "phone number: "不变。

我现在拥有的(下面使用托马斯·马修斯技术)

const char search_text[] = "phone number: ";
std::string::size_type start_posn = example.find(search_text);
std::string::size_type end_posn = example.find(",", start_posn);
const unsigned int length = end_posn - start_posn - sizeof(search_text) - 1;
cout << "length: " << length << endl;
std::string data = example.substr(start_posn, length);
cout << data << endl;

如果我有string example = "phone number: XXXXXXX, Date: XXXXXXXX,"

hmmm,看起来您会搜索"电话号码:",然后在短语后确定索引或位置。您的要求推断出您想要的数据后有一个"。

因此,您想要":"answers"之前的substr。在过去,我们将搜索"并获得其位置。通过减去两个指标获得提取的字符数:
编辑1

const char search_text[] = "phone number: ";
std::string::size_type start_posn = example.find(search_text);
if (start_posn != std::string::npos)
{
   start_posn += sizeof(search_text) - 1;
}
std::string::size_type end_posn   = example.find(",", start_posn);
const unsigned int length = end_posn - start_posn;
std::string data = example.substr(start_posn, length);

注意:以上代码不处理find方法返回std::string::npos的错误情况。

使用上述技术,如何在"日期:"之后提取数据?