C++ 从字符串中提取两个引号

3

我有一个字符串

"John" "你好"

我想将这两个引号中的部分提取出来,以便我可以对它们进行分类。

User: John 
Text: Hello there

我想知道实现这个的最佳方法是什么?是否有可以应用的字符串函数,使这个过程变得简单易行?


可能是最优雅的字符串分割方式?的重复问题。 - 463035818_is_not_a_number
嗯,定义“容易”是什么意思...问题有点含糊...有数不清的方法可以完成它,具有数不清的可能要求... - Massimiliano Janes
2个回答

4

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

在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

添加了实时演示 - 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接