Let us learn how to split string in C++ programming language. We will look at a few ways to split a string.
The splitting of string refers to the grouping of sentences into their individual single word. And splitting is possible only when there is a presence of some delimiters like white space ( ), comma (,), etc. Although there is no straight way to do this as there is no inbuilt function through which we can easily split the string. Hence, we will look at different techniques to split the string in C++.
Different ways of splitting of string in Cpp.
1. Use strtok() function to split strings
How to use strtok: strtok()
function splits the string based on some delimiter. We need to pass the string and the delimiter to this function as shown in the example below.
Syntax for strtok():
char *ptr = strtok( str, delim)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> #include <cstring> using namespace std; int main() { char str[100]; cout << "Enter a string: "; cin.getline(str, 100); char *ptr; ptr = strtok(str, ", "); cout << "\nAfter splitting: " << endl; while (ptr != NULL) { cout << ptr << endl; ptr = strtok(NULL, ", "); } return 0; } |
Output:
Enter a string: This is simple2code.com website
After splitting:
This
is
simple2code.com
website
2. Use std::getline() function to split string
This is another inbuilt function in C++ that extracts characters from the istream
object and stores them into a specified stream until the delimitation character is found.
getline()
function is present in <string> header file. It takes three parameters: string, token, and delimiter.
Syntax for getline():
getline(str, token, delim);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <iostream> #include <string> #include <vector> #include <sstream> using namespace std; int main() { string str, tok; cout << "Enter a string: "; getline(cin, str); // S refers the string str stringstream S(str); //while loop to iterate and print words while (getline(S, tok, ' ')) { cout << tok << endl; } return 0; } |
Output:
Enter a string: This is a coding website
This
is
a
coding
website