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

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 …
Read More

Java Program to Find pair of Integers in Array whose sum is given Number

In this tutorial, we will write a program to find a pair of elements from an array whose sum equals a given number in java …
Read More

Program to Print Diamond Alphabet Patterns in C

In this tutorial, we will learn to write a C program to print Diamond patterns using alphabets/characters. However, in this tutorial, we will create a …
Read More

Half Diamond Pattern in C using Alphabets

In this tutorial, we will learn and code the half diamond alphabet patterns in C programming language. However, in this tutorial, we will create a …
Read More

Half Pyramid of Alphabets in C

In this tutorial, we will learn and code alphabet patterns in C programming language specifically the Half pyramid of alphabets in C programming. However, in …
Read More

Inverted Half Pyramid Pattern of Alphabets in C

In this tutorial, we will write a C program to print half Pyramid using alphabets/characters. Before that, you may go through the following topic in …
Read More