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

C Program to search an element in an array using Pointers

A separate function( search_function()) will be created where the array pointer will be declared and the searched element along with the size of an array …

C Program to find the sum of the digits of a number using recursion function

This C program calculates the sum of digits of a given number using recursion. Here’s a concise explanation: Function Definition: sumDigits(int n) This function calculates …

C program to find factorial of a numberĀ using Ternary operator with Recursion

Recursion refers to the function calling itself directly or in a cycle. Before we begin, you should have the knowledge of following in C Programming: …

C Program to Add Two Numbers Using Call by Reference

The program takes the two numbers from the user and passes the reference to the function where the sum is calculated. You may go through …

Find the output ab, cd, ef, g for the input a,b,c,d,e,f,g in Javascript and Python

In this tutorial, we will write a program to find a pairs of elements from an array such that for the input [a,b,c,d,e,f,g] we will …

String Pattern Programs in C

In this tutorial, we will write various C pattern programs for String. Before that, you may go through the following topics in C. for loop …