简体   繁体   English

C ++,如何标记这个字符串?

[英]C++, how to tokenize this string?

How can I get string like "Ac milan" and "Real Madryt" if they are separated with whitespace? 如果用空格分隔,我怎么能得到像“Ac milan”和“Real Madryt”这样的字符串?

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 doesn't work; 但它不起作用; I have: a= Ac; 我有: a= Ac; b = (null); c=0; d=2;

Yes, sscanf can do what you're asking for, using a scanset conversion: 是的,sscanf 可以使用扫描集转换执行您要求的操作:

#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 output produced by this is: 由此产生的输出是:

Ac milan
Real Madryt
0
2

If you want to go the C++ way, you can use getline , using ; 如果你想采用C ++方式,你可以使用getline ,使用; as the delimiter, as follows. 作为分隔符,如下。

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

Looks like you have ; 看起来你有; as a separator character in the string so you can split the string based on that character. 作为字符串中的分隔符,以便您可以根据该字符拆分字符串。 boost::split is useful for this: boost::split对此非常有用:

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++? 请参阅在C ++中拆分字符串? for other techniques for splitting strings. 用于分割字符串的其他技术。

you can also use the std::string::find_first_of() method that allows you to search for character (delimiters) starting from a given position, eg 你也可以使用std::string::find_first_of()方法,它允许你从给定的位置开始搜索字符(分隔符),例如

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. 然而, boost解决方案是最优雅的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM