×

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

Malloc() and new in C++

In C ++, malloc () and new are used for the same thing. During runtime, they are used to allocate memory. Malloc () and the new, on the other hand,...

4 minutes read.

Binary to Decimal in C++

We must create a software to convert a binary number into an equivalent decimal value given a binary number as input. Example: // C++ program to convert binary to decimal #include < iostream...

3 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

Type conversion in C++

Type conversion is the process of changing the type of variables in a program. The ultimate goal of type conversions is to allow variables of a single data type operate with...

7 minutes read.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

Differences between #define & const in C/C++

 Differences between #define & const in C/C++ A preprocessor directive is #define. The preprocessor replaces things defined by #define prior to starting compilation. In this chapter, we'll learn about the member, variable,...

3 minutes read.

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

User-defined literals in C++

Introduction to User-Defined Literals: User-defined literals, introduced in C++11, are a way to extend the C++ language to allow users to define their literal suffixes and the corresponding behavior. These suffixes...

7 minutes read.

Similarities between C++ and Java

People who are preparing for software engineering roles must have come across either one of these languages because as all the companies do not accept python for hiring a fresher...

3 minutes read.

C++ Inline function

A C++ function that extends in line when called is known as an inline function. It reduces function call overhead by having the compiler use the function code rather than...

4 minutes read.

Decimal to Binary in C++

What is the meaning of Decimal Numbers? Decimal numbers range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two...

3 minutes read.

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The...

7 minutes read.

Vector in C++

Vector in C++ In today’s article, we will be learning all the things about vector in C++ and how vector is different form an array in C++. So basically, vector is very...

3 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

How to create a stack in C++

A stack is a data structure, which is of linear type. A specific order has to be followed while inserting and deleting the elements from the stack. Generally, stack follows...

5 minutes read.

Palindrome Using While Loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

Virtual Functions and Runtime Polymorphism in C++

In this tutorial, we will explore more on virtual functions and runtime polymorphism in the most useful language C++. A virtual function is a member function with the keyword virtual used...

6 minutes read.

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

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