Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break long string into multiple c++

Tags:

c++

string

line

I have a string that is received from third party. This string is actually the text from a text file and it may contain UNIX LF or Windows CRLF for line termination. How can I break this into multiple strings ignoring blank lines? I was planning to do the following, but am not sure if there is a better way. All I need to do is read line by line. Vector here is just a convenience and I can avoid it. * Unfortunately I donot have access to the actual file. I only receive the string object *

string textLine;
vector<string> tokens;

size_t pos = 0;
while( true ) {
    size_t nextPos = textLine.find( pos, '\n\r' );
    if( nextPos == textLine.npos )
        break;
    tokens.push_back( string( textLine.substr( pos, nextPos - pos ) ) );
    pos = nextPos + 1;
}
like image 720
Kiran Avatar asked May 25 '11 15:05

Kiran


People also ask

How do I split a string into multiple strings?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.

What is strtok function in C?

Apr 07, 2007. 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.

Can strtok have multiple delimiters?

The function strtok breaks a string into a smaller strings, or tokens, using a set of delimiters. The string of delimiters may contain one or more delimiters and different delimiter strings may be used with each call to strtok .


1 Answers

You could use std::getline as you're reading from the file instead of reading the whole thing into a string. That will break things up line by line by default. You can simply not push_back any string that comes up empty.

string line;
vector<string> tokens;

while (getline(file, line))
{
    if (!line.empty()) tokens.push_back(line);
}

UPDATE:

If you don't have access to the file, you can use the same code by initializing a stringstream with the whole text. std::getline works on all stream types, not just files.

like image 59
Michael Kristofik Avatar answered Oct 29 '22 02:10

Michael Kristofik