2015-06-21 200 views
0

我有以下字符串名爲標題:"bla bla hello, just more characters filename="myfile.1.2.doc" more characters"如何從cpp中給定的字符串中提取特定的字符串?

我需要的文件名,並從該字符串的文件類型,但我的解決辦法似乎很凌亂(僞代碼):

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最後看?

+0

使用「as a」而不是解析令牌:\「 – user4581301

+0

您需要*轉義*字符串文本中的任何雙引號字符。例如:'header.find(「\」「,// ...);' –

回答

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

第一次迭代給你:
名= myfile.1.2
EXT = DOC
第二種:
名稱= 的newfile
EXT = exe

+0

我應該使用什麼版本的Cpp?我正在嘗試這樣做,但這些都不是我的編譯器所熟悉的。我看到的東西是std :: regexec() \t \t std :: regcomp() – user1386966

+0

它需要C++ 11. 你使用什麼編譯器? – arturx64

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 
} 
相關問題