×

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++.


Related Topics

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

Default Constructor

C++ Default Constructor A default constructor is such constructor which does not take any parameter. A constructor initializes the data member when a class object created. If a programmer does not create any...

2 minutes read.

4-Dimensional Array in C/C++

A four-dimensional (4D) array is an array of three-dimensional (3D) arrays, or in other words we can say that a 4- dimensional array is an array of arrays of arrays...

3 minutes read.

Division in C++

C++ Division Arithmetic Operation In C++ the arithmetic operator / is used for division. This operator takes two operands and returns the result of dividing the left operand by the right...

3 minutes read.

Features of OOPS in C++

What is OOPs? The main reason programmers prefer C ++ language over C is because of the support of object-oriented programing in C++. As the name suggests, object-oriented programming or OOPs...

3 minutes read.

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples. Do-While Loop: The do-while loop constitutes a specific style of looping construct in...

5 minutes read.

Continue in C++ While loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the...

4 minutes read.

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the...

4 minutes read.

C++ Program For FCFS (First Come First Serve)

The most basic scheduling technique is FCFS, often known as "FIFO (First In, First Out)". In this procedure, the first one is utilized and executed first, while the second one...

4 minutes read.

How to improve programming skills in C++

Before getting started, one should know why to improve their programming skills. To become a good software developer or programmer, one must be skilled in at least one programming language. Many...

4 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

C++ Multimap

Definition: In C++, a multimap is similar to a map with the additional concept, where multiple elements possess the same keys. It is also not necessary that the key values and...

4 minutes read.

Assertions in C/C++

Assertions are the statements used to check presumptions which is made by the programmers. Example: Assertion is used to verify whether the malloc returned by the pointer is NULL or not. For...

4 minutes read.

C++ STL (Standard Template Library)

Introduction C++ is a flexible type and general proposed programming language. So we need a standard library that supports C++. C++ STL (Standard Template Library) is a collection of templates that...

6 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

Pointers in C++

Pointers are a powerful feature in the C++ programming language, allowing developers to directly manipulate memory addresses and create more efficient and dynamic programs. However, pointers can also source various...

3 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.

Difference between OOP and POP in C++

Object-Oriented Programming (OOP) Prioritizes data over methods (functions) and treats data as an essential component of program development.  OOP prohibits the free flow of data throughout the system. Tighter ties to data manipulation...

4 minutes read.

Multiset in C++

Introduction Multisets are part of the C++ STL, or Standard Template Library. In C++, a multiset is a set of associative containers that hold ordered items. Items in a multiset can...

10 minutes read.