Pre-requisite
Before checking the examples of this tutorial, you have to check the g++ compiler is installed or not in the system. If you are using Visual Studio Code, then install the necessary extensions to compile the C++ source code to create the executable code. Here, the Visual Studio Code application has been used to compile and execute the C++ code.
Split string using getline() function
The getline() function is used to read characters from a string or a file content until a particular delimiter or separator is found and store each parse string into another string variable. The function will continue the task until the full content of the string or file is parsed. The syntax of this function is given below.
Syntax:
Here, the first parameter, isstream, is the object from where the characters will be extracted. The second parameter is a string variable that will store the extracted value. The third parameter is used to set the delimiter that will use for extracting the string.
Create a C++ file with the following code to split a string based on the space delimiter using the getline() function. A string value of multiple words has been assigned into a variable, and space has been used as the separator. A vector variable has been declared to store the extracted words. Next, the ‘for’ loop has used to print each value from the vector array.
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
int main()
{
//Define string data that will be splitted
std::string strData = "Learn C++ Programming";
//Define contant data that will be worked as delimiter
const char separator = ' ';
//Define the dynamic array variable of strings
std::vector<std::string> outputArray;
//Construct a stream from the string
std::stringstream streamData(strData);
/*
Declare string variable that will be used
to store data after split
*/
std::string val;
/*
The loop will iterate the splitted data and
insert the data into the array
*/
while (std::getline(streamData, val, separator)) {
outputArray.push_back(val);
}
//Print the splitted data
std::cout << "The original string is:" << strData << std::endl;
//Read the array and print the splitted data
std::cout <<
"\nThe values after splitting the string based on space:" <<
std::endl;
for (auto &val: outputArray) {
std::cout << val << std::endl;
}
return 0;
}
Output:
The following output will appear after executing the above code.
Split string using strtok() function
The strtok() function can be used to split a string by tokenizing the part of the string based on a delimiter. It returns a pointer to the next token if it exists; otherwise, it returns a NULL value. The string.h header file is required to use this function. A loop will require reading all splitted values from the string. The first argument contains the string value that will be parsed, and the second argument contains the delimiter that will be used to generate the token. The syntax of this function is given below.
Syntax:
Create a C++ file with the following code to split a string by using the strtok() function. An array of characters is defined in the code containing a colon(‘:’) as the separator. Next, the strtok() function is called with the string value and the delimiter to generate the first token. The ‘while’ loop is defined to generate the other tokens and the token values until the NULL value is found.
#include <stdio.h>
#include <string.h>
int main()
{
//Declare an array of characters
char strArray[] = "Mehrab Hossain :IT Professional :[email protected] :+8801726783423";
//Return the first token value based on ':'
char *tokenValue = strtok(strArray, ":");
//Initialize the counter variable
int counter = 1;
/*
Iterate the loop to print the token value
and split the remaining string data to get
the next token value
*/
while (tokenValue != NULL)
{
if(counter == 1)
printf("Name : %s\n", tokenValue);
else if(counter == 2)
printf("Occupation : %s\n", tokenValue);
else if(counter == 3)
printf("Email : %s\n", tokenValue);
else
printf("Mobile No. : %s\n", tokenValue);
tokenValue = strtok(NULL, ":");
counter++;
}
return 0;
}
Output:
The following output will appear after executing the above code.
Split string using find() and erase() functions
The string can be splitted in C++ by using find() and erase() functions. Create a C++ file with the following code to check the uses of find() and erase() functions to split a string value based on a particular delimiter. The token value is generated by finding the delimiter position by using the find() function, and the token value will be stored after removing the delimiter by using erase() function. This task will be repeated until the full content of the string is parsed. Next, the values of the vector array will be printed.
#include <iostream>
#include <string>
#include <vector>
int main(){
//Define the string
std::string stringData = "Bangladesh and Japan and Germany and Brazil";
//Define the separator
std::string separator = "and";
//Declare the vector variable
std::vector<std::string> country{};
//Declare integer variable
int position;
//Declare string variable
std::string outstr, token;
/*
Split the string using substr() function
and adding the splitted word into the vector
*/
while ((position = stringData.find(separator)) != std::string::npos) {
token = stringData.substr(0, position);
//Remove the extra space from the front of the splitted string
country.push_back(token.erase(0, token.find_first_not_of(" ")));
stringData.erase(0, position + separator.length());
}
//Print all splitted word except the last one
for (const auto &outstr : country) {
std::cout << outstr << std::endl;
}
//Print the last splitted word
std::cout << stringData.erase(0, stringData.find_first_not_of(" ")) << std::endl;
return 0;
}
Output:
The following output will appear after executing the above code.
Conclusion
Three different ways to split a string in C++ have been explained in this tutorial by using simple examples to help the new python users to perform the split operation easily in C++.