2013-02-12 59 views
0

假设我有一个std :: string“55 | 6999 | dkfdfd |”。它共同拥有3部分(每部分后面都有|)。目前我将字符串放到stringstream中,并使用getline来恢复它们。不过,我不知道是否有一个更简单的解决方案,不需要流。我只需要一个简单的方法来从该字符串中使用'|'作为delim,因为我认为流是过度的,我做错了。Get string from string(not from stringstream)

回答

2

如果允许提升,那么boost::split将是一个选项。它可用于填充std::vector<std::string>,其中将包括基于指定的分隔符(S)的领域从输入提取:

#include <vector> 
#include <string> 
using std::vector; 
using std::string; 

#include <boost/algorithm/string.hpp> 
#include <boost/algorithm/string/split.hpp> 
using boost::split; 
using boost::is_any_of; 

vector<string> fields; 
split(fields, "55|6999|dkfdfd|", is_any_of("|")); 
+0

另一个不错的选择,谢谢。 – user1873947 2013-02-12 18:07:35

1

你可以使用std::strtok来代替:

char *token = std::strtok(<yourstring>, "|"); 

< yourstring>必须是char*型的,虽然;然后使用NULL作为之后的那个,std::strtok跟踪以前使用的字符串。

token = std::strtok(NULL, "|"); 
+1

谢谢你,所以我是对的,有一个更好的解决方案。 – user1873947 2013-02-12 18:04:10

+0

@ user1873947,注意'strtok'修改输入,所以使用字符串文字将是非法的,例如。 – hmjd 2013-02-12 18:06:01