How to split a string by newline in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <vector>
#include <sstream>

/**
 * Splits a string by newline characters ('\n') into a collection of lines.
 * 
 * @param str The input string to be split (passed by const reference to avoid copies).
 * @return A std::vector<std::string> containing each individual line.
 */
std::vector<std::string> splitByNewline(const std::string& str) {
    std::vector<std::string> lines;
    std::stringstream ss(str);
    std::string current_line;
    
    // std::getline reads from the stream until it hits a newline ('\n') by default.
    // It safely handles empty lines and correctly terminates at the end of the string.
    while (std::getline(ss, current_line)) {
        lines.push_back(current_line);
    }
    
    return lines;
}

int main() {
    // Input text containing multiple lines
    std::string multiline_text = "Hello world!\nThis is line two.\n\nFinal line here.";

    // Call the splitting function
    std::vector<std::string> result = multiline_text.empty() ? 
        std::vector<std::string>() : splitByNewline(multiline_text);

    // Print out the parsed lines
    for (size_t i = 0; i < result.size(); ++i) {
        std::cout << "Line " << (i + 1) << ": " << result[i] << '\n';
    }
}


/*
run:

Line 1: Hello world!
Line 2: This is line two.
Line 3: 
Line 4: Final line here.

*/

 



answered 1 day ago by avibootz
...