Separating String Tokens Using C std::string
This question addresses the challenge of splitting a C std::string into multiple tokens, particularly using the delimiter ";". While some suggested solutions involve external libraries like Boost, the guidelines for this project prohibit their use. Therefore, we explore a more straightforward approach using the C Standard Library.
One effective method is to utilize the std::getline() function, which offers versatility in specifying delimiters. In this case, we can implement the tokenization process as follows:
#include <sstream> #include <iostream> #include <vector> using namespace std; int main() { vector<string> strings; // Vector to store split strings istringstream f("denmark;sweden;india;us"); // Input stringstream string s; // Variable to store individual strings while (getline(f, s, ';')) { cout << s << endl; // Display split string strings.push_back(s); // Store string in vector } }
In this implementation, we create a stringstream from the input string "denmark;sweden;india;us". The std::getline() function is employed to iterate over the stringstream and retrieve tokens separated by the ";" delimiter. Each retrieved token is both printed and added to the strings vector for further processing.
By employing this approach, we achieve the desired tokenization of the input string without relying on external libraries, adhering to the specified guidelines.
The above is the detailed content of How to Split a String into Tokens in C Using std::getline()?. For more information, please follow other related articles on the PHP Chinese website!