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 !
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.
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!
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With