温馨提示×

c++中string split的用法是什么

小亿
89
2024-02-01 14:30:40
栏目: 编程语言

C++中没有内置的string split函数,但可以自定义实现一个split函数来分割字符串。以下是一个简单的示例代码:

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

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> tokens = split(str, ',');
    for (const std::string& token : tokens) {
        std::cout << token << std::endl;
    }
    return 0;
}

在上述示例代码中,split函数接受一个字符串和一个分隔符作为参数,将字符串按照分隔符进行分割,并返回一个存储分割结果的字符串向量。

首先,使用std::stringstream将输入字符串str转换为流对象ss。然后,使用std::getline函数从ss中逐行读取token,将其加入到tokens向量中。

最后,在main函数中,将字符串"Hello,World,How,Are,You"传递给split函数,分隔符为’,'。然后,使用循环遍历tokens向量中的分割结果,并打印每个分割结果。

运行上述代码的输出结果将是:

Hello
World
How
Are
You

0