c++

c++怎么拆分字符串

小亿
90
2024-08-11 13:26:38
栏目: 编程语言

在C++中,可以使用以下几种方法来拆分字符串:

  1. 使用stringstream类:可以使用stringstream类来将字符串按照指定的分隔符拆分成多个子字符串。
#include <iostream>
#include <sstream>
#include <vector>

int main() {
    std::string str = "Hello,world,this,is,a,test";

    std::stringstream ss(str);
    std::vector<std::string> tokens;
    std::string token;

    while (std::getline(ss, token, ',')) {
        tokens.push_back(token);
    }

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

    return 0;
}
  1. 使用find和substr方法:可以使用find和substr方法来找到分隔符位置并截取子字符串。
#include <iostream>
#include <vector>

int main() {
    std::string str = "Hello,world,this,is,a,test";
    std::string delimiter = ",";

    std::vector<std::string> tokens;
    size_t pos = 0;
    std::string token;

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

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

    return 0;
}

这些方法可以根据具体的需求选择合适的方式来拆分字符串。

0
看了该问题的人还看了