C++ split string by line(C++ 逐行拆分字符串)
问题描述
我需要逐行拆分字符串.我以前是这样做的:
I need to split string by line. I used to do in the following way:
int doSegment(char *sentence, int segNum)
{
assert(pSegmenter != NULL);
Logger &log = Logger::getLogger();
char delims[] = "
";
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;
}
我输入我们是一体的.不,我们是."并调用 doSegment 方法.但是当我调试时,我发现句子参数是we are one.\nyes we are",并且拆分失败.有人可以告诉我为什么会发生这种情况,我应该怎么做.无论如何,我还可以使用其他方法在 C++ 中拆分字符串.谢谢!
I input "we are one. yes we are." and invoke the doSegment method. But when i debugging, i found the sentence parameter is "we are one.\nyes we are", and the split failed. Can somebody tell me why this happened and what should i do. Is there anyway else i can use to split string in C++. thanks !
推荐答案
我想使用 std::getline 或 std::string::find 来遍历字符串.下面的代码演示了 getline 函数
I'd like to use std::getline or std::string::find to go through the string. below code demonstrates getline function
int doSegment(char *sentence)
{
std::stringstream ss(sentence);
std::string to;
if (sentence != NULL)
{
while(std::getline(ss,to,'
')){
cout << to <<endl;
}
}
return 0;
}
这篇关于C++ 逐行拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 逐行拆分字符串


基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16