Home  >  Article  >  Backend Development  >  How to tokenize a std::string using strtok?

How to tokenize a std::string using strtok?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-09 02:41:02925browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn