如何从 cpp 中的给定字符串中提取特定字符串
How to extract specific string from given string in cpp?
我有以下字符串称为header:"bla bla hello, just more characters filename="myfile.1.2.doc" more characters"
我需要从这个字符串中获取文件名和文件类型,但我的解决方案似乎非常混乱(伪代码):
unsigned int end = header.find("filename=");
unsigned int end2 = header.find(" " ", end + sizeof("filename=") + 1) // how to search for ' " ' ?!
std::string fullFileName = header.substr(end +sizeof("filename=") + 1 ,end2 -1);
//now look for the first "." from the end and split by that .
CPP的结尾如何看待?
我认为如果使用正则表达式会更好。
例如:我们有更复杂的字符串,其中包含一些文件名和文件名外的令人困惑的字符,例如 (")。
std::string str("bla bla hello, just more characters filename="myfile.1.2.doc" more characters bla bla hello, just more characters filename="newFile.exe" more char"acters");
std::smatch match;
std::regex regExp("filename="(.*?)\.([^.]*?)"");
while (std::regex_search(str, match, regExp))
{
std::string name = match[1].str();
std::string ext = match[2].str();
str = match.suffix().str();
}
第一次迭代为您提供:
名称 = 我的文件.1.2
分机 = 文档
第二种:
名称 = 新文件
分机 = EXE
size_t startpos = header.find("filename=");
if (startpos != header.npos)
{ // found filename
startpos += sizeof("filename=") - 1; // sizeof determined at compile time.
// -1 ignores the null termination on the c-string
if (startpos != header.length() && header[startpos] == '"')
{ // next char, if there is one, should be "
startpos++;
size_t endpos = header.find('"', startpos);
if (endpos != header.npos)
{ // found terminating ". get full file name
std::string fullfname = header.substr(startpos, endpos-startpos);
size_t dotpos = fullfname.find_last_of('.');
if (dotpos != fullfname.npos)
{ // found dot split string
std::string filename = fullfname.substr(0, dotpos);
//add extra brains here to remove path
std::string filetype = fullfname.substr(dotpos + 1, token.npos);
// dostuff
std::cout << fullfname << ": " << filename << " dot " << filetype << std::endl;
}
else
{
// handle error
}
}
else
{
// handle error
}
}
else
{
// handle error
}
}
else
{
// handle error
}
相关文章:
- 从字符串中提取整数并形成一个数组
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- asn1c 不会从 asn.1 模块中提取八位字节字符串的默认值
- 如何在字符串中找到字符,然后在C++中提取其余的字符串
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 清除输入缓冲区后未提取字符串流
- 如何创建一个函数来提取向量内部字符串中的字段?
- 从没有空格的字符串中提取整数
- 如何使用正则表达式从字符串中提取值
- 使用正则表达式c++从单词和分隔符之间的字符串中提取所有子字符串
- 提取字符串中的随机单词
- 将子字符串提取到最后 n 个分隔符C++
- 如何在C 中不带有弦乐和strtok的情况下拆分字符串(提取单词)
- Arduino中的字符串提取问题
- C++ 在将字符串提取到标量时处理溢出/下溢
- 将两个 '' 字符之间的子字符串提取到单独的数组中
- 字符提取与字符串提取有何不同
- 如何从输入字符串提取数值?c++
- 作为XML字符串提取请求/响应