2012-10-28 121 views
0

可能重复的字符串:
Splitting a string in C++分割使用一个分隔符

我想用一个分隔符为单独的字符串,然后输出每个组串拆分一个字符串对象。

e.g输入的字符串名字,姓氏,年龄,职业,电话

的“ - ”字符是分隔符,我需要输出他们分别只使用String类的功能。

这样做的最好方法是什么?我很难理解.find。 substr和类似的功能。

谢谢!

+0

你可以看看这里的答案:http://stackoverflow.com/questions/236129/s plitting-a-string-in-c – chris

+0

什么是你不了解的功能?如果我们知道,解释你不明白的事情会容易得多。 – chris

回答

0

我会做这样的事情

do 
{   
    std::string::size_type posEnd = myString.find(delim); 
    //your first token is [0, posEnd). Do whatever you want with it. 
    //e.g. if you want to get it as a string, use 
    //myString.substr(0, posEnd - pos); 
    myString = substr(posEnd); 
}while(posEnd != std::string::npos); 
+0

'find'需要一个起始位置来通过第一个位置。 – chris

+0

@chris:是的,没错。修复它 –

2

我觉得字符串流和getline作出易于阅读代码:

#include <string> 
#include <sstream> 
#include <iostream> 

std::string s = "firstname,lastname-age-occupation-telephone"; 

std::istringstream iss(s); 

for (std::string item; std::getline(iss, item, '-');) 
{ 
    std::cout << "Found token: " << item << std::endl; 
} 

下面是使用只string成员函数:

for (std::string::size_type pos, cur = 0; 
    (pos = s.find('-', cur)) != s.npos || cur != s.npos; cur = pos) 
{ 
    std::cout << "Found token: " << s.substr(cur, pos - cur) << std::endl; 

    if (pos != s.npos) ++pos; // gobble up the delimiter 
} 
+0

这种违反使用std :: string成员函数的限制 –

+1

@ArmenTsirunyan:嗯,这是一个耻辱。 –