在C++中,可以使用以下方法对字符串进行分割:

  1. 使用stringstream类:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>

int main() {
    std::string str = "Hello,World,How,Are,You";
    std::vector<std::string> tokens;
    std::stringstream ss(str);
    std::string token;

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

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

    return 0;
}

输出:

Hello
World
How
Are
You
  1. 使用标准库函数strtok:
#include <iostream>
#include <cstring>
#include <vector>

int main() {
    std::string str = "Hello,World,How,Are,You";
    char* cstr = new char[str.length() + 1];
    std::strcpy(cstr, str.c_str());

    std::vector<std::string> tokens;
    char* token = std::strtok(cstr, ",");

    while (token != nullptr) {
        tokens.push_back(token);
        token = std::strtok(nullptr, ",");
    }

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

    delete[] cstr;
    return 0;
}

输出:

Hello
World
How
Are
You

注意:以上示例中,使用了vector容器来保存分割后的字符串。你也可以根据需要选择其他容器,如数组等

c++字符分割

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

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