分割字符串的
问题描述:
喜的朋友,我需要拆分的字符串包含逗号分隔值,并且具有向每个值存储到一个变量中进一步使用该程序。我有我的代码如下:但 我越来越在我的代码中的错误:
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())
{
}
}
}
答
你可以简单地做如下
#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
。
看到这个问题的答案,而不是再次执行它:http://*.com/questions/236129/c-how-to-split-a-string – Naveen 2011-05-04 10:44:56
@Naveen:更确切地说,Feruccio的优秀答案http://*.com/questions/236129/c-how-to-split-a-string/236234#236234 - >使用迭代器进行标记化很便宜! – 2011-05-04 12:02:29