2012-10-26 60 views
2
分手字符串

可能重复:
Split a string into words by multiple delimiters in C++C++使用多个分隔符

我目前正在试图读取每一行都有制表符和空格分隔关键的变化的文件需要插入到二叉树中的属性。

我的问题是:如何使用多个分隔符只使用STL分割一行?我一直试图在这一天的大部分时间里把我的头围绕起来,但无济于事。

任何意见将非常感激。

+1

有此,如现有的许多问题http://stackoverflow.com/questions/7621727/split-a-string-into-words-by-multiple-delimiters-in-c和http://stackoverflow.com/questions/5505965/fast-string-splitting-带多个分隔符 – jogojapan

+0

看看这里http://stackoverflow.com/questions/236129/splitting-a-string-in-c还有纯粹的STL解决方案。 –

回答

2

使用string::find_first_of() [1]

int main() 
{ 
    string str("Replace the vowels in this sentence by asterisks."); 
    size_t found; 

    found = str.find_first_of("aeiou"); 
    while (found != string::npos) { 
    str[found]='*'; 
    found=str.find_first_of("aeiou", found + 1); 
    } 

    cout << str << endl; 

    return 0; 
} 
9

使用std::string::find_first_of

vector<string> bits; 
size_t pos = 0; 
size_t newpos; 
while(pos != string::npos) { 
    newpos = str.find_first_of(" \t", pos); 
    bits.push_back(str.substr(pos, newpos-pos)); 
    if(pos != string::npos) 
     pos++; 
} 
+1

如果第一个字符是其中之一,该怎么办?也许从-1开始'pos',或者在循环之外进行初始搜索? – Xymostech

+1

解决了它,谢谢你的评论。 – nneonneo