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++.
Different method to achieve the splitting of strings in C++
- Use strtok() function to split strings
- Use custom split() function to split strings
- Use std::getline() function to split string
- 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.
Syntax
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.