Splitting a string in C++
Any programming language must have the ability to work with string data. For programming needs, we sometimes need to separate string data. Many computer languages provide a split() method that divides a string into numerous pieces. Although there is no built-in split() method in C++, there are other ways to do the same operation, such utilising the getline(), strtok(), find() and erase() functions, and so on. This tutorial has described how to use these methods to divide strings in C++.
Splitting a string with the getline() method:
The getline() method reads characters from a string or file until a certain delimiter or separator is reached, then stores each parsing string into a separate string variable. The function will keep working until the entire string or file has been parsed. This function's syntax is listed below.
Syntax:
istream& getline(istream& is, string& str, char delim);
The object from which the characters will be taken is the first parameter, istream. The extracted value will be stored in a string variable as the second parameter. The third option is used to provide the delimiter for the string extraction.
Example:
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
void splitstrings(const string &str,
char delimiter,
vector<string>& tokens)
{
stringstream ss(str); //Creating a stringstream object
string words;// this will be used to contain the token(splitted strings)
while(getline(ss,words,delimiter).good())
{
tokens.push_back(words);
}
if (tokens.size()>0)
tokens.push_back(words); // inserting the last token
}
int main()
{
string str="red,blue,green,yellow";
vector<string> vect;
splitstring(str,',',vect);
for(auto s:vect)
{
cout<<s<<"\n";
}
return 0;
}
Output:
red
blue
green
yellow
Explanation:
We created a C++ file containing the above code to divide a string using the getline() method depending on the space delimiter. A variable was allocated a string value of several words, with “,” which is used as a separator. The retrieved words have been saved in a vect vector variable. The 'for' loop was then used to display each value in the vector array. Lastly, the string was separated at all the positions where it had comma “,” and we got a new split string as an output.
Splitting a string Using the strtok() method:
The strtok() method splits a string by quantizing the parts depending on a delimiter. If the next token exists, it returns a reference to it; otherwise, it returns NULL. To utilise this method, we will need the string.h header file. A loop will need reading all of the string's split values. The first input is the string value to be processed, while the second specifies the delimiter to be used to construct the token. This function's syntax is listed below.
Syntax:
char * strtok ( char * str, const char * delimiters );
Example:
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
void tokenizing(std::string const &str, const char* delim,
std::vector<std::string> &out)
{
char *tokens = strtok(const_cast<char*>(str.c_str()), delim);
while (tokens != nullpntr)
{
out.push_back(std::string(tokens));
tokens = strtok(nullpntr, delim);
}
}
int main()
{
std::string strng = "I am an Engineer";
const char* delim = " ";
std::vector<std::string> out;
tokenizing(strng, delim, out);
for (auto &strng: out) {
std::cout << strng << '\n';
}
return 0;
}
Output:
I
am
an
Engineer
Explanation:
To divide a string using the strtok() function, we created a C++ file using this above code. The code defines an array of some characters with a space( ) as the separator. To produce the initial token, the strtok() function is used with a value of string and a delimiter. The 'while' loop generates more tokens and token values again until NULL value is detected. In the main() function the delimiter “ “ occurred in the string it got split and we got our required output.
Using the substr() and find() functions:
In C++, you may split a string by space using the find() and substr() functions. This is a more reliable solution since it can be used to any delimiter.
Example:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void splitStrings(string str, string delimiter = " ")
{
int begin = 0;
int end = str.find(delimiter);
while (end != -1) {
cout << str.substr(begin, end - begin) << endl;
start = end + delimiter.size();
end = str.find(delimiter, begin);
}
cout << str.substr(begin, end - begin);
}
int main()
{
// Splitting the String by using a space in C++
string a = "I want to split a String";
splitString(a, " ");
cout << endl;
return 0;
}
Output:
I
want
to
split
a
String
Explanation:
To divide a string using the find() and substr() function, we created a C++ file using this above code. We created a while loop to know the begin state and the end state of the given string. We used the substr() to split a string on the basis of reference to the begin and the end variables whenever a space occurred if the given condition of the while loop was followed. If the while condition got satisfied and we used the substr() function then the find() function was used to find the delimiter to again begin with
the splitting of string the next time the loop starts. Then in the main() function, the
string is actually split using the delimiter and the required output is displayed.
Conclusion:
This article explains various alternative ways to divide a string in C++ using easy
examples to assist the programming users in performing the split operation in C++.