How to Split a String Based on Empty/Blank Lines in C++?
In C++, strings are objects that represent a sequence of characters and we can break this string into a new line using the ‘\n’ escape sequence. In this article, we will learn how to split a string by empty or blank lines in C++.
Example:
Input: string inputString= "Hello\n\nWorld\n\nThis\n\nis\n\nw3wiki"; Output: Hello World This is w3wiki
Split a String into Words by Empty Lines in C++
To split a std::string by empty lines, we can use the stringstream with a combination of std::getline function having ‘\n’ as the delimiter. We can keep taking input using getline() till there is no string left.
Approach
- Create a stringstream to the given string.
- Create a string variable to store the splitter strings.
- Run a loop using std::getline with ‘\n’ as the delimiter.
- If the line is not empty, add it to the result.
- Repeat the process until the end of the string is reached.
C++ Program to Split a String Based on Empty/Blank Lines
The below program illustrates how we can split a string based on empty/blank lines in C++.
// C++ Program to illustrate how to split a string by empty
// or blank lines
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
// Function to split a string by empty lines
vector<string> splitStringByEmptyLines(string& inputString)
{
vector<string> result;
stringstream ss(inputString);
string line;
// Loop until the end of the string
while (getline(ss, line)) {
if (!line.empty()) {
result.push_back(line);
}
}
return result;
}
int main()
{
// string to be splitted
string inputString
= "Hello\n\nWorld\n\nThis\n\nis\n\nw3wiki";
// calling the function to split the string by empty
// lines
vector<string> substrings
= splitStringByEmptyLines(inputString);
// Displaying the string after splitting
for (const auto& substring : substrings) {
cout << substring << endl;
}
return 0;
}
Output
Hello World This is w3wiki
Time Complexity: O(N)
Auxiliary Space: O(N) , here N is the length of the original string.
Contact Us