dczajkowski
dczajkowski

Reputation: 172

Extract data from c++ string

I wanted to extract the values from the string in C++. I guess this is not the C++ way of doing this, but that one in particular doesn't work. Any ideas?

string line = "{10}{20}Hello World!";
int start;
int end;
string text;

// What to use here? Is the sscanf() a good idea? How to implement it?

cout << start; // 10
cout << end; // 20
cout << text; // Hello World!

Upvotes: 1

Views: 10235

Answers (4)

dczajkowski
dczajkowski

Reputation: 172

Solution using Regular Expressions:

#include <iostream>
#include <regex>

std::string line = "{10}{20}Hello World!";

// Regular expression, that contains 3 match groups: int, int, and anything
std::regex matcher("\\{(\\d+)\\}\\{(\\d+)\\}(.+)");

std::smatch match;
if (!std::regex_search(line, match, matcher)) {
  throw std::runtime_error("Failed to match expected format.");
}

int start = std::stoi(match[1]);
int end = std::stoi(match[2]);
std::string text = match[3];

Upvotes: 1

Xavier Ara&#250;jo
Xavier Ara&#250;jo

Reputation: 171

You could use the method String.find() to get the positions of '{' and '}' and then extract the data you want through String.substr().

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Although you can make sscanf work, this solution is more appropriate for C programs. In C++ you should prefer string stream:

string s("{10}{20}Hello World!");
stringstream iss(s);

Now you can use the familiar stream operations for reading input into integers and strings:

string a;
int x, y;
iss.ignore(1, '{');
iss >> x;
iss.ignore(1, '}');
iss.ignore(1, '{');
iss >> y;
iss.ignore(1, '}');
getline(iss, a);

Demo.

Upvotes: 3

PMonti
PMonti

Reputation: 460

text does not need to have an "&" in front of it inside the sscanf, since string names are already pointers to their starting address.

sscanf(line, "{%d}{%d}%s", &start, &end, text);

Upvotes: -2

Related Questions