Ways to Split a String in C++

1.Introduction

2.Logic of Splitting a String

This, is a, string, to split
This
is a
string
to split

3.Using C++ Built-in(Native) Functions

3.1.Using strtok() function

char * strtok ( char * str, const char * delimiters );
1.Get input as string
2.Convert C++ string to C string
3.while delimiter is found in string:
3.1.Split the string using the strtok() function
4.Postprocess
Splitted string:
Split
this
string.

3.2.Using string::rfind() function with string::substr() function

1.Get input as string
2.while delimiter is found in string:
2.1.Use rfind() function to find the position of the rightmost delimiter
2.2.Create a substring by excluding the part of the string which starts after rightmost delimiter using substr()
2.3.Create a substring which is token itself using substr()
3.Postprocess
5
4
3
2
1

3.3.Using string::rfind() function with string::substr() function and string::erase() function

1.Get input as string
2.while delimiter is found in string:
2.1.Use rfind() function to find the position of the rightmost delimiter
2.2.Create a substring by excluding the part of the string which starts after rightmost delimiter using erase()
2.3.Create a substring which is token itself using substr()
3.Postprocess
5
4
3
2
1

3.4.Using string::find() function with string::substr() function

1.Get input as string
2.while delimiter is found in string:
2.1.Use find() function to find the position of the leftmost delimiter
2.2.Create a substring by excluding the part of the string which starts after leftmost delimiter using substr()
2.3.Create a substring which is token itself using substr()
3.Postprocess
1
2
3
4
5

3.5.Using stringstream with getline() function

1.Get input as string
2.Create stringstream object by passing the input string
3.while the results returned by getline() is not empty:
3.1.Process tokens
4.Postprocess
1
2s
3
4
5
6

4.Storing Tokens

4.1. Using Arrays

1
2s
3
4
5
6

4.2. Using Vectors

1
2s
3
4
5
6

5. Notes

Further

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store