How to Split String by space in C++

Split String by space in C++

In this article, we will see how to split String by space in C++.

C++ provide so many ways and Methods to Split The String Splitting a string by some delimiter is a common task. For example, we have to read list of elements separated by comma from a file and we want to get individual elements from the list.

A typical solution might look like the following:

The std::split() algorithm takes a std::string_view and a delimiter as arguments, and it returns a range of std::string_view objects as output. The std::string_view objects in the returned range will refer to sub strings of the input text. The delimiter object defines the boundaries between the returned sub string.

There are many ways to split String by space in C++.

Using getline() Method

We can use std::getline() method which simplifies character from istream object and then stored them into vector until the delimitation character found.
Let’s understand with the help of example.

Output :

This
is
java2blog

Using std::strtok

We can also use std::strtok to split String by space in C++. std:strtok returns next token. We need to call this in loop to get all the tokens. It will return null when there are no more tokens left in the String.

Output :

we
are
professional
blogger

Using find and substr methods

You can use string’s find() and substr() methods to Split String by space in C++. This is more robust solution as this can be used for any delimeter.
Here is the code:

Output :

How
to
split
String
in
C++

Using istringstream

We first create an object of the class istringstream which copies the content of the string passed as argument. We can then use getline() to split the String by space in C++.

Output :

This
is
C++
blog

Using User Define Functions

In this program, I used arrange function, which is a userdefined function to split the string

Output :

I
like
to
play
cricket

That’s all about how to split String by space in C++

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.