What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

How to Split a String in C++? 6 Easy Methods (with Codes)

  • Nov 14, 2023
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Anubhav Agarwal
How to Split a String in C++? 6 Easy Methods (with Codes)

Splitting a string into individual words is a common task in programming. It allows us to process and manipulate text data more efficiently. While C++ doesn't have a built-in split function, there are several methods and techniques we can use to achieve this. In this article, we will explore six different approaches to splitting strings in C++. Let's learn about all of them!

6 Methods to Split a String in C++

Here is the list of those methods which you can use to split a string into words using your own delimiter function:

  1. Using Temporary String
  2. Using stringstream API of C++
  3. Using strtok() Function
  4. Using Custom split() Function
  5. Using std::getline() Function
  6. Using find(), substr() and erase() Functions

Now, to split a string we must specify on what basis we are going to do it, here comes the delimiter. So, splitting strings is only possible with specific delimiters such as white space( ), comma(,), hyphen(-), and so on, resulting in individual words. 

1) Using Temporary String

In this example, we are first taking input from the user using getline() function, and the separator variable is used as a delimiter to separate the string using commas.

Then, we are iterating to the end of the string, if we do not find our space delimiter, then we will continue adding chars to my temp string and if in between we found our delimiter then, just print that string and make it empty as shown in the below example:

// Welcome to Favtutor 
#include<bits/stdc++.h>

#include

using namespace std;

int main() {
    char arr[100];
    
    // Input using the getline function.
    cin.getline(arr, 100); 
    char separator = ' ';
    int i = 0;
    
    // Temporary string used to split the string.
    string s; 
    while (arr[i] != '\0') {
        if (arr[i] != separator) {
            // Append the char to the temp string.
            s += arr[i]; 
        } else {
            cout << s << endl;
            s.clear();
        }
        i++;

    }
    
    // Output the last stored word.
    cout << s << endl; 
}

 

Input:

I love to read articles on the scaler topics.

 

Output:

I
love
to
read 
articles 
on 
the
scaler
topics.

 

2) Using stringstream API of C++

You need to know about stringstream first.

We use cin stream to take input from the user, similarly, we first initialize the stringstream's object and take the input in it using "<<" operator which allows it to read a string as a stream of words. 

The most commonly used stringstream operators are as follows:

  • Operator<<: pushes a string object into the stream.
  • Operator>>: extracts a word from the stream.

Note: Tokenizing a string means splitting it with respect to a delimiter.

Syntax of stringstream object:

stringstream  obj_name(string string_name);

 

In this method, we will first create a stringstream object which will take the string and split it into words automatically. To read those words we will create a variable word and we will read all the words till my stringstream object exhaust. 

// Welcome to Favtutor
#include <bits/stdc++.h>
using namespace std;
 
int main() {
    string s = "I love to read articles on Favtutor.";
    
    // Takes only space separated C++ strings.
    stringstream ss(s);  
    string word;
    while (ss >> word) { // Extract word from the stream.
        cout << word << endl;
    }
    cout << endl;
    return 0;
}


Output:

I
love
to
read 
articles 
on 
Favtutor.

 

3) Using strtok() Function

The strtok() function is a widely-used method to split strings in C++. The strtok() function splits the string into tokens based on the delimiter passed. The strtok() function modifies the original string on each call by inserting the NULL character (\0) at the delimiter position. This allows it to track the status of the token easily.

Syntax:

char *ptr = strtok (string, delimiter);

 

Here, the string is the given which we want to split, delimiter is the parameter or character based on which we separate the string. It returns a pointer to the next character tokens. It initially points to the first token of the strings.

In this method, we are first taking string as input using getline() function and then creating a pointer of type char and using strtok() function with space as a delimiter, it will give us each word. For that, we run a loop until the char pointer is not equal to NULL. In each iteration, we print the pointer.

//Welcome to Favtutor
#include <bits/stdc++.h>

#include

using namespace std;
int main() {
    char s[100];
    cin.getline(s, 100);

    // Pointer to point the word returned by the strtok() function.
    char * p;
    // Here, the delimiter is white space.
    p = strtok(s, " "); 
    while (p != NULL) {
        cout << p << endl;
        p = strtok(NULL, " ");
    }

}

 

Input:

I love to read articles on Favtutor.

 

Output:

I
love
to
read 
articles 
on 
Favtutor.

 

4) Using Custom split() Function

If you prefer a more customized approach, you can create your own split() function. In this method, we are using for loop to iterate over the entire string until we find our delimiter. If found, then we will append up to that string into a vector of temp string and update the startIndex and endIndex accordingly. Here, we are defining our own custom function to split a string in C++. 

// Welcome to favtutor
#include
#include<bits/stdc++.h>
using namespace std;
 
vector < string > strings;
// Create custom split() function.  
void customSplit(string str, char separator) {
    int startIndex = 0, endIndex = 0;
    for (int i = 0; i <= str.size(); i++) {
        
        // If we reached the end of the word or the end of the input.
        if (str[i] == separator || i == str.size()) {
            endIndex = i;
            string temp;
            temp.append(str, startIndex, endIndex - startIndex);
            strings.push_back(temp);
            startIndex = endIndex + 1;
        }
    }
}

int main() {
    string str = "I love to read articles on Favtutor.";
    // Space is used as a separator.
    char separator = ' '; 
    customSplit(str, separator);
    cout << " The split string is: " << endl;
    for (auto it: strings) {
        cout << it << endl;
    }

    return 0;
} 

 

Output:

The split string is:
I
love
to
read 
articles 
on 
Favtutor.

 

5) Using std::getline() Function

 Another method to split strings in C++ is by using the std:::getline() function. This function reads a string from an input stream until a delimiter character is encountered.  Just as we take the input from the user using getline() function, similarly we will take the input into the sringstream using getline() function.

Syntax:

getline(string, token, delimiter);

 

Here, the token saves the extracted string tokens from the original string. Below is the C++ program implementation:

// Welcome to favtutor
#include <bits/stdc++.h>  
using namespace std;  
   
int main() {
    string s, str;

    s = "I love to read articles on Favtutor.";

    // ss is an object of stringstream that references the S string.  
    stringstream ss(s); 

    // Use while loop to check the getline() function condition.  
    while (getline(ss, str, ' ')) 
        // `str` is used to store the token string while ' ' whitespace is used as the delimiter.
        cout << str << endl;

    return 0;
} 

 

Output:

I
love
to
read 
articles 
on 
Favtutor.

 

 6) Using find(), substr() and erase() Functions

An alternative approach to split strings in C++ is by using the find() and substr() functions. The find() function searches for a specified substring within a string, while the substr() function extracts a substring from a given position. In this method, we will use the find(), substr(), and erase() function to split the given string using our delimiter. 

Syntax:

string substr (size_t position, size_t length);

 

Note: The substr() returns a string object and size_t is an unsigned integer type. Below is the C++ program implementation :

// Welcome to Favtutor
#include <bits/stdc++.h>
using namespace std;
 
void find_str(string s, string del) {
    // Use find function to find 1st position of delimiter.
    int end = s.find(del); 
    while (end != -1) { // Loop until no delimiter is left in the string.
        cout << s.substr(0, end) << endl;
        s.erase(s.begin(), s.begin() + end + 1);
        end = s.find(del);
    }
    cout << s.substr(0, end);
}

int main() {
    string a = "I love to read articles on Favtutor."; 
    // Here, the delimiter is white space.
    string del = " "; 
    find_str(a, del);

    return 0;
}

 

Output:

I
love
to
read 
articles 
on 
Favtutor.

 

You can also check out this article: String Interpolation.

Conclusion 

In this article, we learned about the various methods involved to take words out of the given string or to split a string based on the delimiter passed. In competitive programming, you will find most of the time the use of this operation accordingly. By understanding these techniques, you will have the necessary knowledge to manipulate string data effectively in your C++ programs.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Anubhav Agarwal
I'm a research-oriented engaged in various technologies and a technical content writer. Being a coder myself, going through the documentation to provide optimized solutions as technical content is what I always look for.