我需要逐行拆分字符串。我以前是这样做的:
int doSegment(char *sentence, int segNum)
{
assert(pSegmenter != NULL);
Logger &log = Logger::getLogger();
char delims[] = "\n";
char *line = NULL;
if (sentence != NULL)
{
line = strtok(sentence, delims);
while(line != NULL)
{
cout << line << endl;
line = strtok(NULL, delims);
}
}
else
{
log.error("....");
}
return 0;
}我输入“我们是一体的\n是的”并调用doSegment方法。但当我调试时,我发现句子参数是“我们是一体的。\n是的,我们是一体的”,拆分失败。谁能告诉我为什么会这样,我该怎么做。还有没有别的方法可以用来在C++中拆分字符串。谢谢!
发布于 2012-11-01 15:14:33
我想使用std::getline或std:: string ::find来遍历字符串。下面的代码演示了getline函数
int doSegment(char *sentence)
{
std::stringstream ss(sentence);
std::string to;
if (sentence != NULL)
{
while(std::getline(ss,to,'\n')){
cout << to <<endl;
}
}
return 0;
}发布于 2012-11-01 15:08:17
您可以在循环中调用std::string::find并使用std::string::substr。
std::vector<std::string> split_string(const std::string& str,
const std::string& delimiter)
{
std::vector<std::string> strings;
std::string::size_type pos = 0;
std::string::size_type prev = 0;
while ((pos = str.find(delimiter, prev)) != std::string::npos)
{
strings.push_back(str.substr(prev, pos - prev));
prev = pos + 1;
}
// To get the last substring (or only, if delimiter is not found)
strings.push_back(str.substr(prev));
return strings;
}请参阅示例here。
发布于 2019-12-10 20:29:57
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split_string_by_newline(const std::string& str)
{
auto result = std::vector<std::string>{};
auto ss = std::stringstream{str};
for (std::string line; std::getline(ss, line, '\n');)
result.push_back(line);
return result;
}https://stackoverflow.com/questions/13172158
复制相似问题