Hit enter after type your search item

3 Examples to Split String in C++ by Comma and Space

How to split string in C++?

In this tutorial, we will show you ways of splitting a string by comma and space in C++.

There are different ways you can achieve this task.

Using stringstream and getline() function to split string

We can use getline() function and stringstream to split strings in C++. First, have a look at the following C++ program and then I will explain how it worked:


Output:

CPP-split-string-space

You can see, the above string is split by a space delimiter. So, how it worked?

  • We associated a string object (str_Spl) to stringstream. Stringstream allows reading from the string.
  • The getline() is used. It takes three parameters including the delimiter. There you may specify a space, comma, or any other desired character that you want to split a string.
  • You may learn more about getline() function in its tutorial.

Using comma as delimiter to split strings in C++

The program below splits the string by comma delimiter.


Output:

CPP-split-string-comma

Taking user input for source string to split

In this example, we take the input from the user to enter the string to split by space delimiter.


Sample Output:

CPP-split-user-input

 

This div height required for enabling the sticky sidebar