Through Web service i'm downloading a file as a string. Now the string is having the whole file. I want to extract line by line in that string. Can any one help in how to do this?
string::find( char c, size_type pos = 0 ) returns the index of the first occurrence of c in the string beginning at index pos.
string::substr( size_type pos = 0, size_type n = npos ) returns the substring of n characters beginning from, and including, the character at index 'pos'.
algorithm:
find the first \n
while one found
get the substring from the beginning up to the \n
set the string equal to the substring beginning immediately after the \n through the end of the string
find the first \n
Dear God, people. Is this the "Let's do things the most roundabout way possible" week and no one told me?
I don't know who I would fail with the lower grade if I was a teacher and smilodon and Kiana were my students.
On Windows platform, a new line is represented by Carriage Return Line Feed (CRLF), a combination of Enter key on keyboard and new line character. In other words "\r\n"... Here goes a simple simple code...
Assuming strInput is the input string, coming in from any source...
Use of non-standard elements and use of over-complicated algorithms for a relatively simple task. Never forget the KISS principle. The more complex an algorithm, the harder it is to maintain and the more likely it is to contain bugs.
how would you have done it?
Depends on how much emphasis on portability and efficiency is needed.
If none and none then:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <sstream>
#include <vector>
//Assumes only '\n' is used as the newline.
std::vector<std::string> splitIntoLines(const std::string &string){
std::stringstream stream(string);
std::vector<std::string> res;
while (1){
std::string line;
std::getline(stream,line);
if (!stream.good())
break;
res.push_back(line);
}
return res;
}
smilodon had the right idea, but he twisted it beyond recognition.
If you want to add some efficiency in there, don't use the copy constructor on the return value (work over a reference instead), and avoid vector in deference of deque:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <sstream>
#include <string>
#include <vector>
void splitIntoLines(
std::deque <std::string> &result,
const std::string &s
) {
std::istringstream ss( s );
std::string line;
while (std::getline( ss, line )) {
result.push_back( line );
}
}