Home » How to Split strings in C++

How to Split strings in C++

by Online Tutorials Library

How to Split strings in C++?

This topic will discuss how we can split given strings into a single word in the C++ programming language. When we divide a group of words or string collections into single words, it is termed the split or division of the string. However, splitting strings is only possible with some delimiters like white space ( ), comma (,), a hyphen (-), etc., making the words an individual. Furthermore, there is no predefined split function to divide the collection of strings into an individual string. So, here we will learn the different methods to split strings into a single one in C++.

How to Split strings in C++

Different method to achieve the splitting of strings in C++

  1. Use strtok() function to split strings
  2. Use custom split() function to split strings
  3. Use std::getline() function to split string
  4. Use find() and substr() function to split string

Use strtok() function to split strings

strtok(): A strtok() function is used to split the original string into pieces or tokens based on the delimiter passed.


In the above syntax, a strtok() has two parameters, the str, and the delim.

str: A str is an original string from which strtok() function split strings.

delim: It is a character that is used to split a string. For example, comma (,), space ( ), hyphen (-), etc.

Return: It returns a pointer that references the next character tokens. Initially, it points to the first token of the strings.

Note: A strtok() function modifies the original string and puts a NULL character (‘

You may also like