2011-03-31 46 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解決方案是最優雅的。