c++

c++的split()函数怎么使用

小亿
298
2023-12-15 15:23:21
栏目: 编程语言

C++标准库中没有提供内置的split函数,但可以使用一些其他方法来实现类似的功能。以下是一种常见的实现方法:

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

std::vector<std::string> split(const std::string& str, char delimiter) {
    std::vector<std::string> tokens;
    std::stringstream ss(str);
    std::string token;
    
    while (std::getline(ss, token, delimiter)) {
        tokens.push_back(token);
    }
    
    return tokens;
}

int main() {
    std::string str = "Hello,World,How,Are,You";
    std::vector<std::string> result = split(str, ',');
    
    for (const auto& s : result) {
        std::cout << s << std::endl;
    }
    
    return 0;
}

在上述代码中,我们定义了一个split函数,该函数接受一个字符串和一个分隔符作为参数,并返回一个存储了被分割后的子字符串的vector。我们使用istringstream来将输入字符串拆分为子字符串,并使用getline函数从istringstream中读取每个子字符串。每次读取到分隔符时,将子字符串添加到tokens vector中。最后,我们在主函数中调用split函数,并打印分割后的子字符串。

0
看了该问题的人还看了