首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在C++中拆分不带空格的字符串

在C++中拆分不带空格的字符串可以使用以下方法:

方法一:使用stringstream和getline函数

代码语言:txt
复制
#include <iostream>
#include <sstream>
#include <vector>

int main() {
    std::string str = "Hello,World,C++,String,Split";
    std::vector<std::string> result;
    std::stringstream ss(str);
    std::string token;

    while (getline(ss, token, ',')) {
        result.push_back(token);
    }

    for (const auto& s : result) {
        std::cout << s << std::endl;
    }

    return 0;
}

这种方法使用stringstream将字符串转换为流,然后使用getline函数按照指定的分隔符(这里是逗号)进行分割,并将分割后的子串存储到vector中。

方法二:使用find和substr函数

代码语言:txt
复制
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::string str = "Hello,World,C++,String,Split";
    std::vector<std::string> result;
    size_t pos = 0;
    std::string delimiter = ",";

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

    for (const auto& s : result) {
        std::cout << s << std::endl;
    }

    return 0;
}

这种方法使用find函数找到分隔符的位置,然后使用substr函数提取子串,并将子串存储到vector中。循环进行直到找不到分隔符为止。

以上两种方法都可以实现在C++中拆分不带空格的字符串。根据具体的需求和场景选择合适的方法。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券