如何提取C 中的字符/字符串之间的字符串
How do you extract a string that is in between a char/string in C++?
假设我有一个简单的字符串:
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
的错误情况。
使用上述技术,如何在"日期:"之后提取数据?
相关文章:
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 两个字符串之间的数学运算
- 目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)
- 我需要在C++的两个字符串之间找到共同的前缀
- 如何在没有映射的情况下在枚举和字符串之间进行转换?
- 正则表达式匹配字符串之间的数字
- 如何更有效地计算n个字符串之间的不匹配分数?
- 最接近的字符串:在字符串阵列中找到2个字符串之间的最小距离
- 在字符串之间插入字符
- STD :: cin和Scanf()应用于字符串之间的区别
- 使用 c++ 获取两个日期与时间字符串之间的差异(以秒为单位)
- 如何在C 中的字符串之间留出空间
- 在文本中的两个非唯一字符串之间获取子弦
- 假定相同的字符串之间的比较失败' == '比较
- C++提取两个字符串之间的数据
- C++ 和 pascal 字符串之间的区别
- 如何在C++中获取子字符串并在字符串之间添加字符
- 在C++代码中,如何让用户在2个文本字符串之间输入一个数字
- 如何在Visual C 中的BSTR和32位Unicode字符串之间进行转换