This section will explore the process of breaking down provided strings into individual words within the C++ programming language. When we separate a cluster of words or a series of strings into individual words, it is referred to as splitting or dividing the string. Nonetheless, the act of splitting strings can only be achieved using specific delimiters such as blank spaces , commas (,), hyphens (-), and others to isolate the words. Additionally, there is no built-in split function available to separate a set of strings into individual strings. Hence, we will delve into various techniques for splitting strings into singular entities in C++.
Different method to achieve the splitting of strings in C++
- Use strtok function to split strings
- Use custom split function to split strings
- Use std::getline function to split string
- Use find and substr function to split string
Use strtok function to split strings
The strtok function is employed to divide the initial string into fragments or tokens according to the specified delimiter.
Syntax
char *ptr = strtok( str, delim)
In the given syntax, a strtok function includes two arguments, the str for the string to be tokenized, and the delim for the delimiter characters.
A string, referred to as a "str," serves as the initial string that the strtok function divides into substrings.
A delimiter is a character utilized to separate a string, such as a comma (,), space , hyphen (-), and so forth.
It provides a pointer that points to the subsequent character tokens. At the beginning, it points to the first token within the string.
Note: A strtok function modifies the original string and puts a NULL character ('\0') on the delimiter position on each call of the strtok function. In this way, it can easily track the status of the token.
Program to split strings using strtok function
Let's explore a demonstration on how to separate a string in C++ by employing the strtok function.
Program.cpp
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[100]; // declare the size of string
cout << " Enter a string: " <<endl;
cin.getline(str, 100); // use getline() function to read a string from input stream
char *ptr; // declare a ptr pointer
ptr = strtok(str, " , "); // use strtok() function to separate string using comma (,) delimiter.
cout << " \n Split string using strtok() function: " << endl;
// use while loop to check ptr is not null
while (ptr != NULL)
{
cout << ptr << endl; // print the string token
ptr = strtok (NULL, " , ");
}
return 0;
}
Output
Enter a string:
Learn how to split a string in C++ using the strtok() function.
Split string using strtok() function:
Learn
how
to
split
a
string
in
C++
Using
the
strtok()
function.
Program to use custom split function to split strings
Let's develop a C++ program that divides strings into separate parts by utilizing a personalized split function.
Program2.cpp
#include <iostream>
#include <string>
#define max 8 // define the max string
using namespace std;
string strings[max]; // define max string
// length of the string
int len(string str)
{
int length = 0;
for (int i = 0; str[i] != '\0'; i++)
{
length++;
}
return length;
}
// create custom split() function
void split (string str, char seperator)
{
int currIndex = 0, i = 0;
int startIndex = 0, endIndex = 0;
while (i <= len(str))
{
if (str[i] == seperator || i == len(str))
{
endIndex = i;
string subStr = "";
subStr.append(str, startIndex, endIndex - startIndex);
strings[currIndex] = subStr;
currIndex += 1;
startIndex = endIndex + 1;
}
i++;
}
}
int main()
{
string str = "Program to split strings using custom split function.";
char seperator = ' '; // space
split(str, seperator);
cout <<" The split string is: ";
for (int i = 0; i < max; i++)
{
cout << "\n i : " << i << " " << strings[i];
}
return 0;
}
Output
The split string is:
i : 0 Program
i : 1 to
i : 2 split
i : 3 strings
i : 4 using
i : 5 custom
i : 6 split
i : 7 function.
Use std::getline function to split string
A getline function is a built-in function in C++ that is employed to input a string from a stream and store it in a string vector until specific delimiter characters are encountered. To utilize the std::getline function, it is necessary to include the <string> header file.
Syntax
getline(str, token, delim);
It has three parameters:
A str is a variable designed to hold the original string value.
It holds the string tokens that have been extracted from the original string.
A delimiter is a character utilized to separate parts of a string. Common examples include the comma (,), space , hyphen (-), and so on.
Program to use getline function to split strings
Let's explore a case where strings are divided using the getline function in C++.
Program3.cpp
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
string S, T; // declare string variables
getline(cin, S); // use getline() function to read a line of string and store into S variable.
stringstream X(S); // X is an object of stringstream that references the S string
// use while loop to check the getline() function condition
while (getline(X, T, ' ')) {
/* X represents to read the string from stringstream, T use for store the token string and,
' ' whitespace represents to split the string where whitespace is found. */
cout << T << endl; // print split string
}
return 0;
}
Output
Welcome to the Cpp Tutorial and Learn C++ Programming Language.
Welcome
to
the
Cpp Tutorial
and
Learn
C++
Programming
Language.
Program to split the given string using the getline function
Let's explore a demonstration on dividing a provided string in C++ utilizing the getline function.
Program4.cpp
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
void split_str( std::string const &str, const char delim,
std::vector <std::string> &out )
{
// create a stream from the string
std::stringstream s(str);
std::string s2;
while (std:: getline (s, s2, delim) )
{
out.push_back(s2); // store the string in s2
}
}
int main()
{
std:: string s2 = "Learn How to split a string in C++";
const char delim = ' '; /* define the delimiter like space (' '), comma (,), hyphen (-), etc. */
std::cout << "Your given string is: " << s2;
std::vector <std::string> out; // store the string in vector
split_str (s2, delim, out); // call function to split the string
// use range based for loop
for (const auto &s2: out)
{
std::cout << "\n" << s2;
}
return 0;
}
Output
Your given string is: Learn How to split a string in C++
Learn
How
to
split
a
string
in
C++
Use find and substr function to split strings
Let's create a C++ program that utilizes the find function along with the substr function to divide provided strings.
Program4.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
// given string with delimiter
string given_str = "How_to_split_a_string_using_find()_and_substr()_function_in_C++";
string delim = "_"; // delimiter
cout << " Your string with delimiter is: " << given_str << endl;
size_t pos = 0;
string token1; // define a string variable
// use find() function to get the position of the delimiters
while (( pos = given_str.find (delim)) != std::string::npos)
{
token1 = given_str.substr(0, pos); // store the substring
cout << token1 << endl;
given_str.erase(0, pos + delim.length()); /* erase() function store the current positon and move to next token. */
}
cout << given_str << endl; // it print last token of the string.
}
Output
Your string with delimiter is: How_to_split_a_string_using_find()_and_substr()_function_in_C++
How
to
split
a
string
using
find()
and
substr()
function
in
C++
In the preceding code snippet, we employ a find method within the loop to iteratively locate the delimiter's position in the specified string, subsequently dividing it into distinct tokens upon encountering the delimiter. The substr function captures the substring intended for output. Conversely, using the erase function retains the current string position and advances to the subsequent token, with this sequence persisting until all segmented strings have been extracted.