3

I have a string

"John" "Hello there"

I'm looking to extract the quotes into two strings so that I can categorize them like.

User: John 
Text: Hello there

I was wondering what the best way to do this is? Is there a string function that can be applied to make this an easy process?

user1692517
  • 1,122
  • 4
  • 14
  • 28

2 Answers2

4

Use std::quoted: http://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";
    }
}

Note it also supports escaping quotes: if the input is Me "This is a \"quoted\" word", it will print (also Live)

User: Me
Text: This is a "quoted" word
sehe
  • 374,641
  • 47
  • 450
  • 633
1

This is a possible solution that uses 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;
  }

Output:

Jhon
Hello There
Neb
  • 2,270
  • 1
  • 12
  • 22