How to Split a String in C++2 min read

Let us learn how to split string in C++ programming language. We will look at a few ways to split a string.

The splitting of string refers to the grouping of sentences into their individual single word. And splitting is possible only when there is a presence of some delimiters like white space ( ), comma (,), etc. Although there is no straight way to do this as there is no inbuilt function through which we can easily split the string. Hence, we will look at different techniques to split the string in C++.


Different ways of splitting of string in Cpp.

1. Use strtok() function to split strings

How to use strtok: strtok() function splits the string based on some delimiter. We need to pass the string and the delimiter to this function as shown in the example below.

Syntax for strtok():

char *ptr = strtok( str, delim)  

Output:

Enter a string: This is simple2code.com website

After splitting:
This
is
simple2code.com
website


2. Use std::getline() function to split string

This is another inbuilt function in C++ that extracts characters from the istream object and stores them into a specified stream until the delimitation character is found.

getline() function is present in <string> header file. It takes three parameters: string, token, and delimiter.

Syntax for getline():

getline(str, token, delim); 

Output:

Enter a string: This is a coding website
This
is
a
coding
website


MORE

Find a pair with the Given Sum in an Array in Java

In this tutorial, we will write a java program to find the sum pair in an array. Before that, you may go through the following …
Read More

C++ Program to display Pascal Triangle

In this tutorial, we will write a C++ program to display pascal’s triangle. Before that, you may go through the following topic in C++. for …
Read More

C++ Program to Calculate Sum of Geometric Progression

In this tutorial, we will learn and write a program to find the sum of GP series in C++. Before that, you may go through …
Read More

C++ Program to find the Transpose of a Matrix

In this tutorial, we will learn and write a program to find the transpose of matric in C++. Before that, you may go through the …
Read More

How to Split a String in C++

Let us learn how to split string in C++ programming language. We will look at a few ways to split a string. The splitting of …
Read More

C++ Program to calculate Average of Numbers using Arrays

In this tutorial, we will learn and write a C++ program to find the average of numbers using an array. To understand the coding, you …
Read More