Home >Backend Development >C++ >How can std::getline() be used to split strings with tokens in C ?
Using getline() to Split Strings with Tokens
When working with strings in C , it becomes necessary to split them into smaller segments based on specific delimiters. One common method to achieve this is using the std::getline() function, which provides a flexible way to extract substrings based on tokenized delimiters.
In the given scenario, where we have a string composed of words separated by semicolons, we can use std::getline() to efficiently split the string into individual components. The following code snippet demonstrates how to implement this:
#include <sstream> #include <iostream> #include <vector> using namespace std; int main() { vector<string> strings; istringstream f("denmark;sweden;india;us"); string s; while (getline(f, s, ';')) { cout << s << endl; strings.push_back(s); } }
In this code, we begin by creating a vector to store the split strings. We then pass the target string, "denmark;sweden;india;us," into an istringstream object, which allows us to treat the string as a stream.
The key operation is the use of getline() to extract substrings until we reach the end of the stream. The getline() function takes three parameters: the input stream, a reference to a string to store the extracted substring, and a delimiter character. In this case, we use a semicolon as the delimiter to split the string at each occurrence.
Within the loop, we retrieve each substring by calling getline() and store it in the string variable s. We then output the substring for confirmation and add it to the strings vector for further processing.
By following this approach, we can effectively split a string based on tokens or delimiters, making it easier to handle individual segments as needed.
The above is the detailed content of How can std::getline() be used to split strings with tokens in C ?. For more information, please follow other related articles on the PHP Chinese website!