如何从cpp中的给定字符串中提取特定字符串?

时间:2015-06-21 17:01:09

标签: c++ string split substring

我有以下名为header的字符串:SELECT s.ymd, s.symbol, s.price_close FROM stocks s DISTRIBUTE BY s.symbol SORT BY s.symbol ASC, s.ymd ASC;

我需要从这个字符串中获取文件名和文件类型,但我的解决方案似乎非常混乱(伪代码):

"bla bla hello, just more characters filename="myfile.1.2.doc" more characters"

如何从cpp的结尾看?

2 个答案:

答案 0 :(得分:2)


我认为如果你使用正则表达式会更好 例如:我们有更复杂的字符串,文件名和文件名之外的(“)等字符混淆。

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();
}

第一次迭代为您提供:
name = myfile.1.2
ext = doc
第二:
name = newfile
ext = exe

答案 1 :(得分:0)

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
}