How to Split strings in C++
Sometimes we need to split a string into multiple substrings based on a delimiter. C++ provides several ways to accomplish this task.
Syntax
#include <string>
#include <sstream>
using namespace std;
string input = "this-is-a-test-string";
stringstream ss(input);
string part;
while (getline(ss, part, '-')) {
// do something with each part
}
In the above example, we define a stringstream and initialize it with our string. We then use the getline function with a delimiter to extract each part of the string.
Example
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string input = "this,is,a,test,string";
vector<string> parts;
stringstream ss(input);
string part;
while (getline(ss, part, ',')) {
parts.push_back(part);
}
// print each part
for (auto p : parts) {
cout << p << endl;
}
return 0;
}
Output
this
is
a
test
string
Explanation
In the above example, we define a string called "input" that contains several substrings separated by commas. We then create a vector to store each substring.
We use a stringstream to extract each part of the string using the getline function. The second argument to getline is the delimiter, which in this case is a comma.
Each extracted part is added to the vector using the push_back function. Finally, we print each part of the vector to the console.
Use
Splitting strings can be useful in a variety of scenarios, such as parsing input from a user or reading data from a file.
Important Points
- C++ provides several ways to split strings, including using stringstreams and the strtok function.
- The getline function can be used to extract each part of a string based on a delimiter.
- The extracted parts can be stored in a vector or other container for further processing.
Summary
In summary, splitting strings in C++ can be accomplished using a variety of techniques. The stringstream and getline functions provide a simple and flexible way to extract each part of a string based on a delimiter.