2011-03-31 43 views
4

如何将字符串“Ac milan”和“Real Madryt”与空格分隔开来?C++,如何标记这个字符串?

这里是我的尝试:

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); 

,但它不工作;我有:a= Ac;b = (null); c=0; d=2;

+0

看到我的解决方案:标记化一串数据转化为结构向量?](http://stackoverflow.com/questions/5462022/tokenizing-a-string-of-data-into-a-vector-of-structs/5462907#5462907) – Nawaz 2011-03-31 15:41:25

+0

个人,我偏爱自己的解决方案。 :) http://stackoverflow.com/questions/3046747/c-stl-selective-iterator/3047106#3047106 – 2011-03-31 15:42:49

+1

顺便说一下,这是皇马,不是真正的马德里:) – 2011-03-31 15:51:13

回答

7

是,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; 
} 

由此产生的输出是:

Ac milan 
Real Madryt 
0 
2 
+0

太棒了!谢谢:) – 2011-03-31 16:34:35

+0

不要喜欢scanf,而是使用长度说明符,以避免缓冲区溢出。 – 2011-03-31 16:41:22

6

如果你想要去的C++的方式,你可以使用getline,使用;作为分隔符,如下所示。

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

该死的,打我吧。 – 2011-03-31 15:36:44

+0

@Jerry:谢谢。我'不知道有关scanset转换。我相应地改变了我的答案。为你+1。 – 2011-04-01 08:33:07

3

看起来你有;为字符串,因此您可以拆分根据该字符的字符串分隔符。 boost::split是这个有用:

string linia = "Ac milan ; Real Madryt ; 0 ; 2"; 
list<string> splitresults; 

boost::split(splitresults, linia, boost::is_any_of(";")); 

其他技术分割字符串见Split a string in C++?

1

您还可以使用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); 

但是,boost解决方案是最优雅的。