如何用c++ string匹配实现字符串分割

c++
915
2024/9/25 12:31:40
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

你可以使用C++标准库中的<sstream><string>头文件来实现字符串分割功能。下面是一个简单的示例代码:

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

std::vector<std::string> split(const std::string& str, char delim) {
    std::istringstream iss(str);
    std::string token;
    std::vector<std::string> tokens;

    while (std::getline(iss, token, delim)) {
        tokens.push_back(token);
    }

    return tokens;
}

int main() {
    std::string str = "C++ is a powerful programming language.";
    char delim = ' ';

    std::vector<std::string> tokens = split(str, delim);

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

    return 0;
}

在上面的代码中,我们定义了一个split函数,它接受一个字符串和一个分隔符作为参数。该函数使用std::istringstream类从输入字符串中读取数据,并使用std::getline函数按分隔符将字符串分割为多个子字符串。最后,这些子字符串被存储在一个std::vector<std::string>对象中并返回。

main函数中,我们调用split函数来分割一个示例字符串,并将结果打印到控制台上。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++中strncpy函数的作用是什么