Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ split string by line

Tags:

c++

split

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[] = "\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; } 

I input "we are one.\nyes 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 !

like image 372
wangzhiju Avatar asked Nov 01 '12 06:11

wangzhiju


People also ask

How can I split a string in C?

Splitting a string using strtok() in C In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.

How do I write a multi line string literal in C?

We can use string literal concatenation. Multiple string literals in a row are joined together: char* my_str = "Here is the first line." "Here is the second line."; But wait!

What is strtok function in C?

The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token.


1 Answers

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,'\n')){       cout << to <<endl;     }   }  return 0; } 
like image 100
billz Avatar answered Sep 27 '22 21:09

billz