c++

有哪些C++库支持类似strtok_r的功能

小樊
84
2024-08-29 18:33:47
栏目: 编程语言

在 C++ 中,有多个库和函数可以实现类似 strtok_r 的功能,这里列出了一些常用的方法:

  1. C++ 标准库中的std::string类及其成员函数find, substr` 等。

例子:

#include<iostream>
#include<string>

int main() {
    std::string str = "This is a test string";
    std::string delimiter = " ";
    size_t pos = 0;
    std::string token;

    while ((pos = str.find(delimiter)) != std::string::npos) {
        token = str.substr(0, pos);
        std::cout<< token<< std::endl;
        str.erase(0, pos + delimiter.length());
    }
    std::cout<< str<< std::endl;

    return 0;
}
  1. 使用 <sstream> 库中的 std::istringstreamstd::getline 函数。

例子:

#include<iostream>
#include <sstream>
#include<string>

int main() {
    std::string str = "This is a test string";
    std::string delimiter = " ";
    std::istringstream iss(str);
    std::string token;

    while (std::getline(iss, token, delimiter[0])) {
        std::cout<< token<< std::endl;
    }

    return 0;
}
  1. 如果你喜欢使用正则表达式,可以使用` 库。

例子:

#include<iostream>
#include<string>
#include<regex>

int main() {
    std::string str = "This is a test string";
    std::regex delimiter("\\s+");
    std::sregex_token_iterator it(str.begin(), str.end(), delimiter, -1), end;

    for (; it != end; ++it) {
        std::cout << *it<< std::endl;
    }

    return 0;
}
  1. 使用 Boost 库中的 boost::split 函数。

首先需要安装并包含 Boost 库,然后:

#include<iostream>
#include<string>
#include<vector>
#include<boost/algorithm/string.hpp>

int main() {
    std::string str = "This is a test string";
    std::vector<std::string> tokens;
    boost::split(tokens, str, boost::is_any_of(" "));

    for (const auto& token : tokens) {
        std::cout<< token<< std::endl;
    }

    return 0;
}

这些方法都可以实现类似 strtok_r 的功能,根据你的需求和项目环境选择合适的方法。

0
看了该问题的人还看了