我有一个字符串
"John" "你好"
我想将这两个引号中的部分提取出来,以便我可以对它们进行分类。
User: John
Text: Hello there
我想知道实现这个的最佳方法是什么?是否有可以应用的字符串函数,使这个过程变得简单易行?
使用std::quoted
: http://en.cppreference.com/w/cpp/io/manip/quoted
#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
这是一种可能的解决方案,使用了 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