分割字符串的

问题描述:

可能重复:
C++: How to split a string?分割字符串的

喜的朋友,我需要拆分的字符串包含逗号分隔值,并且具有向每个值存储到一个变量中进一步使用该程序。我有我的代码如下:但 我越来越在我的代码中的错误:

string myString = ........// i am getting the string from a function 
string::iterator it = myString .begin(); 
while (it != myString .end()) 
{ 
     if (*it == ',') 
     { 
      string element =*it++; //i can't do such type of conversion.but then how can 
            i get each value ? 
      if(element.empty()) 
      { 
      } 
     } 
} 
+1

看到这个问题的答案,而不是再次执行它:http://*.com/questions/236129/c-how-to-split-a-string – Naveen 2011-05-04 10:44:56

+0

@Naveen:更确切地说,Feruccio的优秀答案http://*.com/questions/236129/c-how-to-split-a-string/236234#236234 - >使用迭代器进行标记化很便宜! – 2011-05-04 12:02:29

你可以简单地做如下

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

std::string String = "Your,String,is,here"; 
char Separator = ','; 

std::istringstream StrStream(String); 
std::string Token; 

while(std::getline(StrStream, Token, Separator)) 
{ 
    std::cout << Token << "\n"; 
} 

我会建议使用一些可用库作为升压字符串工具http://www.boost.org/doc/libs/1_46_1/doc/html/string_algo.html

如果您需要手动实现它,我不会用迭代器,而是std::string::find获得元件中的每一个,然后开始和结束位置std::string::substr

这里以前回答,

C++ ostream out manipulation

我认为必须有更优雅的解决方案在这里对SO,但是这一次至少包括单元测试:)