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

How to tokenize a std::string using strtok?

Mary-Kate Olsen
Release: 2024-11-09 02:41:02
Original
926 people have browsed it

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template