C++ has no split() function, so you cannot call one directly. You can write a small helper named split that returns the pieces of a string as a std::vector<std::string>. Once the helper exists, you call it in much the same way you would call split() in Python or C#.
Why C++ has no split()
The C++ standard library keeps std::string small. It has find, substr and replace, but no method that splits text. The closest standard tool is std::views::split, added in C++20. It is a range adaptor, so you pipe a string into it with |, and it returns views over the original text rather than a list of strings.
Write a split helper
This helper wraps std::getline and a std::stringstream. Put it at the top of your file or in a header:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> split(const std::string& text, char delimiter) {
std::vector<std::string> pieces;
std::stringstream stream(text);
std::string piece;
while (std::getline(stream, piece, delimiter)) {
pieces.push_back(piece);
}
return pieces;
}
int main() {
std::vector<std::string> numbers = split("4,8,15,16,23,42", ',');
for (const std::string& number : numbers) {
std::cout << number << '\n';
}
}
The program prints the six numbers, one per line.
Call the helper with a single char delimiter. Single quotes make a char, so ',' works. Double quotes make a string, so "," does not match the helper’s signature and will not compile. For the details of how the stream approach handles empty pieces, see How to Use getline() and stringstream in C++.
How split() works in other languages
Python and C# both have a split method on their string types, which is why the name is familiar:
- In Python,
str.split()returns a list. How to Split a String With a Delimiter in Python covers it in detail. - In C#,
string.Split()returns an array of strings. What Does Split() Do in C#? covers it in detail.
The C++ helper above does a similar job, but it returns a vector and takes one character as the delimiter.
Use Boost for split()
If your project already uses the Boost libraries, boost::split from <boost/algorithm/string.hpp> fills a vector and takes a predicate such as boost::is_any_of(","). That adds a dependency, so the helper above is enough for most small programs.
If you see a compiler error
Calling split() without defining it gives an error that the name is undeclared. Add the helper above, or include the header that declares your own version.
The helper handles any single-character delimiter and returns a vector you can loop over. For a delimiter longer than one character, use the find() and substr() approach instead.