Home > Article > Backend Development > How to tokenize a std::string using strtok?
Tokenizing a std::string with strtok
Tokenizing a std::string using strtok requires converting it into a char for compatibility. However, trying to use str.c_str() results in a const char type, which is not suitable for strtok.
One solution is to use an istringstream object, which allows you to treat a string as a sequence of tokens. Here's an example:
#include <iostream> #include <string> #include <sstream> int main() { std::string myText("some-text-to-tokenize"); std::istringstream iss(myText); std::string token; // Use getline() to extract tokens separated by '-' while (std::getline(iss, token, '-')) { std::cout << token << std::endl; } return 0; }
Alternatively, consider using the Boost C Libraries, which provide additional string manipulation and tokenization functions, offering more flexibility and control.
The above is the detailed content of How to tokenize a std::string using strtok?. For more information, please follow other related articles on the PHP Chinese website!