在C++20中,可以使用std::split函数来根据字符串分割字符串。std::split函数接受三个参数:要分割的字符串,分割符号和输出迭代器。

下面是一个例子,演示如何使用std::split函数来分割字符串:

#include <iostream>
#include <string>
#include <ranges>

int main() {
    std::string str = "apple,banana,orange";
    std::ranges::split(str, ',', std::ostream_iterator<std::string>(std::cout, "\n"));
    return 0;
}

输出结果为:

apple
banana
orange

在上面的例子中,我们使用std::ranges::split函数来分割字符串。第一个参数是要分割的字符串,第二个参数是分割符号,这里我们使用逗号。第三个参数是输出迭代器,我们使用std::ostream_iterator来将分割出来的字符串输出到标准输出流中。

需要注意的是,std::split函数返回一个std::ranges::split_view对象,该对象可以用于惰性分割字符串。例如,我们可以先创建一个std::ranges::split_view对象,然后使用for循环逐个输出分割出来的字符串:

#include <iostream>
#include <string>
#include <ranges>

int main() {
    std::string str = "apple,banana,orange";
    auto split_view = std::ranges::split(str, ',');
    for (const auto& s : split_view) {
        std::cout << s << '\n';
    }
    return 0;
}

输出结果和上面的例子一样。

c++20 实现根据字符串分割字符串

原文地址: https://www.cveoy.top/t/topic/sEF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录