How to Split String in C++: Simple Methods and Examples
In C++, you can split a string using
std::getline with a delimiter inside a std::stringstream. This method reads parts of the string separated by the delimiter and stores them into smaller strings.Syntax
To split a string by a delimiter, use std::stringstream to read the string and std::getline to extract tokens separated by the delimiter.
std::string input: The original string to split.std::stringstream ss(input): Creates a stream from the string.std::getline(ss, token, delimiter): Reads from the stream until the delimiter is found.token: Holds each part of the split string.
cpp
std::string input = "apple,banana,cherry"; std::stringstream ss(input); std::string token; while (std::getline(ss, token, ',')) { // token contains each split part }
Example
This example splits a comma-separated string into parts and prints each part on a new line.
cpp
#include <iostream> #include <sstream> #include <string> int main() { std::string input = "apple,banana,cherry"; std::stringstream ss(input); std::string token; while (std::getline(ss, token, ',')) { std::cout << token << std::endl; } return 0; }
Output
apple
banana
cherry
Common Pitfalls
One common mistake is to try splitting without using std::stringstream, which does not work directly on strings. Another is forgetting to specify the delimiter in std::getline, which defaults to newline and won't split by commas or other characters.
Also, be careful with empty tokens if delimiters are adjacent.
cpp
/* Wrong way: Trying to use std::getline directly on std::string */ std::string input = "a,b,c"; std::string token; // std::getline(input, token, ','); // Error: no matching function /* Right way: Use stringstream */ std::stringstream ss(input); while (std::getline(ss, token, ',')) { // process token }
Quick Reference
Tips for splitting strings in C++:
- Use
std::stringstreamto treat strings like streams. - Use
std::getlinewith a delimiter to extract tokens. - Remember the delimiter defaults to newline if not specified.
- Check for empty tokens if delimiters are next to each other.
Key Takeaways
Use std::stringstream with std::getline to split strings by a delimiter in C++.
Always specify the delimiter in std::getline to split on characters other than newline.
std::stringstream allows you to treat strings like input streams for easy parsing.
Watch out for empty tokens when delimiters appear consecutively.
Direct splitting without stringstream is not supported in standard C++.