Splitting a string means dividing it into smaller substrings based on a delimiter such as a space, comma, or special character.
- C++ provides multiple ways to split strings depending on the delimiter and required control.
- stringstream, find() with substr(), and manual traversal can be used for this task.
Examples
Input: str = "How do you do!"
Delimiter: Space
Output:How
do
you
do!Input: str = "Hi$%do$%you$%do$%!"
Delimiter: $%
Output:Hi
do
you
do
!
Approaches to Split a String
The following approaches can be used to split a string in C++:
1. Using stringstream
stringstream is useful when the string needs to be split into words separated by whitespace. The extraction operator (>>) automatically skips consecutive spaces.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
void splitString(const string& str)
{
stringstream ss(str);
string word;
while (ss >> word) {
cout << word << '\n';
}
}
int main()
{
string str = "How do you do!";
splitString(str);
return 0;
}
Output
How do you do!
Explanation: The string is passed to a stringstream, which treats whitespace as the separator. Each >> operation extracts the next word and automatically ignores consecutive spaces.
2. Using find() and substr()
When the delimiter can be any string, including a multi-character delimiter such as $%, find() and substr() provide more control.
#include <iostream>
#include <string>
using namespace std;
void splitString(const string& str, const string& delimiter)
{
size_t start = 0;
size_t end;
while ((end = str.find(delimiter, start)) != string::npos) {
cout << str.substr(start, end - start) << '\n';
start = end + delimiter.length();
}
cout << str.substr(start) << '\n';
}
int main()
{
string str = "Hi$%do$%you$%do$%!";
string delimiter = "$%";
splitString(str, delimiter);
return 0;
}
Output
Hi do you do !
Explanation: find() locates the next occurrence of the delimiter, while substr() extracts the characters between two delimiter positions. After each substring is extracted, start is moved past the delimiter and the process continues until the complete string is processed.
3. Using Manual String Traversal
If the delimiter is a single character, the string can be traversed directly without using a stream or repeated find() calls.
#include <iostream>
#include <string>
using namespace std;
void splitString(const string& str, char delimiter)
{
string current;
for (char ch : str) {
if (ch == delimiter) {
cout << current << ' ';
current.clear();
}
else {
current += ch;
}
}
cout << current;
}
int main()
{
string str = "geeks_for_geeks";
char delimiter = '_';
splitString(str, delimiter);
return 0;
}
Output
geeks for geeks
Explanation: The program scans the string character by character and stores characters in current. Whenever the delimiter is encountered, the current substring is printed and cleared. After the traversal, the remaining characters form the last substring.