C ++, how tokenize this string?

How can I get a string like "Ac milan" and "Real Madryt" if they are separated by spaces?

Here is my attempt:

string linia = "Ac milan ; Real Madryt ; 0 ; 2"; str = new char [linia.size()+1]; strcpy(str, linia.c_str()); sscanf(str, "%s ; %s ; %d ; %d", a, b, &c, &d); 

but it does not work; I have: a= Ac; b = (null); c=0; d=2;

+4
source share
4 answers

Yes, sscanf can do what you ask using scan conversion:

 #include <stdio.h> #include <iostream> #include <string> int main(){ char a[20], b[20]; int c=0, d=0; std::string linia("Ac milan ; Real Madryt ; 0 ; 2"); sscanf(linia.c_str(), " %19[^;]; %19[^;] ;%d ;%d", a, b, &c, &d); std::cout << a << "\n" << b << "\n" << c << "\n" << d << "\n"; return 0; } 

The result created by this:

 Ac milan Real Madryt 0 2 
+7
source

If you want to switch to C ++, you can use getline using ; as a delimiter as shown below.

 string s = "Ac milan ; Real Madryt ; 0 ; 2"; string s0, s1; istringstream iss(s); getline(iss, s0, ';'); getline(iss, s1, ';'); 
+6
source

It looks like you have ; as a separator character in a string so that you can split the string based on that character. boost::split is useful for this:

 string linia = "Ac milan ; Real Madryt ; 0 ; 2"; list<string> splitresults; boost::split(splitresults, linia, boost::is_any_of(";")); 

See Split a String in C ++? for other line splitting methods.

+3
source

You can also use the method of std::string::find_first_of() , which lets you search for the character (Comma), starting at the specified position, for example.

 size_t tok_end = linia.find_first_of(";", prev_tok_end+1); token = linia.substr(prev_tok_end+1, prev_tok_end+1 - tok_end); 

However, the boost solution is the most elegant.

+1
source

Source: https://habr.com/ru/post/1346080/


All Articles