How to split string in C++?
In this tutorial, we will show you ways of splitting a string by comma and space in C++.
There are different ways you can achieve this task.
Using stringstream and getline() function to split string
We can use getline() function and stringstream to split strings in C++.
First, have a look at the following C++ program and then I will explain how it works:
#include <iostream> #include <sstream> using namespace std; int main() { string str_Spl, str_piece; //String to split str_Spl = "C++ is cool program language, love it!"; //Creating an object of stringstream stringstream obj_ss(str_Spl); cout <<"Source String to Split: " <<str_Spl << "\n\n"; // getline() function to go through source string until it is finished. while (getline(obj_ss, str_piece, ' ')) { cout << str_piece << endl; } return 0; }
Output:
You can see, the above string is split by a space delimiter.
So, how it worked?
- We associated a string object (str_Spl) to stringstream. Stringstream allows reading from the string.
- The getline() is used. It takes three parameters including the delimiter. There you may specify a space, comma, or any other desired character that you want to split a string.
- You may learn more about getline() function in its tutorial.
Using comma as delimiter to split strings in C++
The program below splits the string by comma delimiter.
#include <iostream> #include <sstream> using namespace std; int main() { string str_Spl, str_piece; //String to split str_Spl = "Banana,Mango,Apple,Grapes"; //Creating an object of stringstream stringstream obj_ss(str_Spl); cout <<"Source String to Split: " <<str_Spl << "\n\n"; // while loop function to go through source string until it is finished. while (getline(obj_ss, str_piece, ',')) { cout << str_piece << endl; } return 0; }
Output:
Taking user input for source string to split
In this example, we take the input from the user to enter the string to split by space delimiter.
#include <iostream> #include <sstream> using namespace std; int main() { string str_Spl, str_piece; //Taking User Input cout << "Enter a line to split by space? "; getline(cin, str_Spl); stringstream obj_ss(str_Spl); // while loop function to go through source string until it is finished. cout << "\nString after Split: \n\n "; while (getline(obj_ss, str_piece, ' ')) { cout << str_piece << endl; } return 0; }
Sample Output: