2017-10-10 65 views
2

我有一个字符串C++字符串中的

“约翰”“你好提取两个引号”

我期待引号提取到两个字符串,这样我可以将它们分类喜欢。

User: John 
Text: Hello there 

我想知道要做到这一点的最好办法是什么?有没有一个字符串函数可以用来使这个过程简单?

+0

的可能的复制(https://stackoverflow.com/questions/236129/most-elegant-way-to-split-a-string) – user463035818

+0

uhm,定义'easy'...这个问题有点模糊......有gazilion的做法,有gaziliion可能的要求... –

回答

3

使用std::quotedhttp://en.cppreference.com/w/cpp/io/manip/quoted

Live On Coliru

#include <iomanip> 
#include <sstream> 
#include <iostream> 

int main() { 
    std::string user, text; 

    std::istringstream iss("\"John\" \"Hello there\""); 

    if (iss >> std::quoted(user) >> std::quoted(text)) { 
     std::cout << "User: " << user << "\n"; 
     std::cout << "Text: " << text << "\n"; 
    } 
} 

注意它也支持转义引号:如果输入的是Me "This is a \"quoted\" word",将打印(也Live

User: Me 
Text: This is a "quoted" word 
+0

添加了现场演示 – sehe

1

这是一个使用一个可能的解决方案stringstream

std::string name = "\"Jhon\" \"Hello There\""; 
    std::stringstream ss{name}; 
    std::string token; 

    getline(ss, token, '\"'); 
    while (!ss.eof()) 
    { 
     getline(ss, token, '\"'); 
     ss.ignore(256, '\"'); 

     std::cout << token << std::endl; 
    } 

输出:?最优雅的方式来分割字符串]

Jhon 
Hello There