Table of contents
1.
Introduction
2.
What is Split String in C++?
3.
Methods of Splitting a String in C++
3.1.
1. The strtok() Function
3.1.1.
Syntax
3.1.2.
Algorithm
3.1.3.
Program
3.2.
C++
3.2.1.
Output:
3.3.
2. The find() and substr() Functions
3.3.1.
Syntax
3.3.2.
Algorithm
3.3.3.
Program
3.4.
C++
3.4.1.
Output:
3.5.
3. The getline() Function
3.5.1.
Syntax
3.5.2.
Algorithm
3.5.3.
Program
3.6.
C++
3.6.1.
Output:
4.
Frequently Asked Questions
4.1.
How many types of strings are supported by C++?
4.2.
What is split () in C++?
4.3.
What is the best way to split a string in C?
4.4.
How to split a string in C without function?
4.5.
How do you split a string number?
5.
Conclusion
Last Updated: Apr 4, 2024
Medium

C++ Split String

Author Amit Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Have you worked on strings in C++? Do you know how to split a string in C++? 

C++ Split String

In C++, a string is like an object. It represents a sequence or collection of characters. This article is focused on C++ split string or splitting a string using different methods or functions. We will learn these methods in detail.

Also see, Fibonacci Series in C++

What is Split String in C++?

In C++, string is like to an object, embodying a series or gathering of characters. It's a frequently encountered operation to divide a string into substrings using a specified delimiter. From interpreting user input to processing data files, this activity is invaluable in a variety of applications. Developers can efficiently handle and modify strings, increasing the usefulness and adaptability of their applications, by using methods like tokenization or specialized libraries.

For example, let’s assume a string Coding:Ninjas. It has the colon (:) delimiter. We can split the string from the colon into two parts. One will be Coding and the other one will be Ninjas.

Methods of Splitting a String in C++

We can split it using different functions like:

  1. The strtok() function,
     
  2. The find() and substr() functions, and
     
  3. The getline() Function.
     

Let's see these functions in depth.

1. The strtok() Function

The first method we will discuss is the strtok() method. We can use this method to split a string. In this method, the string is split by tokenizing a small part of the string with delimiters. The function will return a pointer to the next token only if it exists. If not, it will return a NULL value.

We need the string.h header file to use this function. We will also need a loop to read all the split parts of the string. The first argument will be the string value that you want to parse. The second argument will be the delimiter you want to use to make the token.

Let's check out the syntax of this function.

Syntax

char *pointr = strtok(string, delimiter);

 

This function has two arguments:

  • string: This is the original string.
     
  • delimiter: This is a character. It will be used to split the string.
     
  • This function returns a pointer referring to the next token of characters.
     

Algorithm

  1. The first step is to create a C++ file.
     
  2. Then we will define a character array and take input from the user.
     
  3. Now we will split the string by calling strrok() function. But it will create only the first token.
     
  4. So, we will use the while loop to generate other tokens until we have received the NULL value.
     
  5. We will print the result as well.
     

Program

  • C++

C++

//C++ Split String Program using strtok() function.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
  
   // Here, we will store the string.
   char strArr[100];
   
   cout << " Please enter the String that you want to split: " << endl;
   cin.getline(strArr, 100);

   // Using the strtok() function for C++ split string.
   char *pointr;
   pointr = strtok(strArr, ":");
   cout << "Here, we are going to split the string using strtok() function:" << endl;

   while(pointr!=NULL) {

       cout << pointr << endl;
       pointr = strtok(NULL,":");
   }

   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:
output

Try and compile with online c++ compiler.

2. The find() and substr() Functions

Now we are going to use the substr() method. We can split a string with delimiters. We will split the string based on the delimiter into several strings.  

Let's check out the syntax of this function.

Syntax

string.substr(start, end);


This function is called using the original string and the dot (.) operator. 

It has two arguments:

  • start: This is the start position from where you want to split the string.
     
  • end: This is the end position.
     

Algorithm

  1. The first step is to create a C++ file.
     
  2. Then we will define a character array and take input from the user.
     
  3. Now, we will use the find() function to find the occurrence of the delimiter.
     
  4. Each time we find the delimiter, we will use the substr() function to get the part of the string inside a while loop.
     
  5. We will print the result as well.
     

Program

  • C++

C++

// C++ Split String program using find() and substr() methods.
#include <iostream>
#include <string>
using namespace std;

void splitstring(string strArr, string delimiter = " ") {
  
   // Starting and Ending Index.
   int starting = 0;
   int ending = strArr.find(delimiter);

   // While Loop.
   while (ending!=-1) {
       // Using the substr() function for C++ split string.
       cout << strArr.substr(starting, ending-starting) << endl;
       starting = ending + delimiter.size();
       ending = strArr.find(delimiter, starting);
   }
   cout << strArr.substr(starting, ending-starting);
}

int main() {
  
   // Here, we will store the string.
   char strArr[100];
  
   cout << "Please enter the String that you want to split: " << endl;
   cin.getline(strArr, 100);
  
   cout << "Here, we are going to split the string using find() and substr() functions:" << endl;

   // Calling the splitstring function.
   splitstring(strArr, ":");
   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:
output

Also check out - Substr C++

3. The getline() Function

We can also use the getline() function to split a string. The approach is a little bit different this time. We will read the string from an input stream and put it into a vector string. We will keep doing it until we have found any delimiter. 

It is a standard library function of the C++ programming language. We can import the <string> header file to use the std::getline() function.

Let's check out the syntax of this function.

Syntax

getline(string, token, delimiter);

 

This function has three parameters:

  • string: It is the original string.
     
  • delimiter: It is a character that will be used to split the string.
     
  • token: It will store the string tokens retrieved from the string. 
     

Algorithm

  1. The first step is to create a C++ file.
  2. Then we will define a character array and take input from the user.
  3. We will now use a vector variable to store the retrieved words.
  4. Finally, we will use the 'for' loop to traverse the vector array.
  5. We will print the result as well.

Program

  • C++

C++

// C++ Split String program using getline() methods.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;

int main() {
  
   // Here, we will store the string and the tokens.
   string strArr;
   string tokens;
  
   cout << "Please enter the String that you want to split: " << endl;
   getline(cin, strArr);

   // Object of String Stream referencing to the string.
   stringstream teststream(strArr);

   cout << "Here, we are going to split the string using getline() functions:" << endl;

   // while loop to print the split string using stringstream for C++ split string.
   while(getline(teststream, tokens, ':')) {       
       cout << tokens << endl;
   }

   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:
output

Check out this article - String slicing in Python

Frequently Asked Questions

How many types of strings are supported by C++?

C++ programming language supports two types of strings: The C-String in the header file “cstring” and the C++ string class in the header file “string.”

What is split () in C++?

A split() is not a built-in function in C++. To split a string, you can use techniques like using std::getline() with a delimiter or implement a custom function that separates the string based on a specified criterion.

What is the best way to split a string in C?

The best way to split a string in C is by using the strtok() function from the C standard library. It allows you to tokenize a string based on a specified delimiter, making it a versatile and efficient choice for string splitting tasks.

How to split a string in C without function?

Without using built-in functions like strtok(), one way to split a string in C is by iterating through each character of the string, detecting the delimiter, and copying substrings into separate buffers. However, this method can be complex and error-prone compared to using standard library functions.

How do you split a string number?

To split a string containing numbers in C, you can employ similar techniques as splitting regular strings. Use delimiter detection or specific parsing algorithms to separate the numbers based on your requirements. Additionally, standard library functions like strtok() can be utilized for this purpose.

Conclusion

In this article, we have discussed how to Split strings in C++? Understanding the splitting of strings in C++ opens doors to versatile programming solutions. Whether you're handling user input, data manipulation, or text processing, knowing how to split strings effectively is invaluable.

We hope that this article has provided you with the help to enhance your knowledge regarding C++ split string and if you would like to learn more, check out our articles on c++ vector erase, and vectors of vectors in c

Recommended Articles:

Recommended problems -


Do check out The Interview guide for Product Based Companies as well as some of the Popular interview problems from top tech companies like Amazon, Adobe, Google, Uber, Microsoft, etc. on Coding Ninjas Studio.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available; take a look at the interview experiences and interview bundle for placement preparations.

Live masterclass