首页
学习
活动
专区
工具
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++中拆分不带空格的字符串。根据具体的需求和场景选择合适的方法。

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

相关·内容

C++中对字符串的分割

由于C++中没有split函数,因此,为了能够对获取的字符串进行按一定符号进行分割,在此学习了通过字符串的find()方法和substr()方法来实现split();具体描述如下:  //涉及到string类的两个函数find和substr:  //  //1、find函数  //原型: size_t find(const string& str, size_t pos = 0) const;  //功能: 查找子字符串第一次出现的位置。  //参数说明:str为子字符串,pos为初始查找位置。  //返回值: 找到的话返回第一次出现的位置,否则返回string::npos  //2、substr函数  //原型: string substr(size_t pos = 0, size_t n = npos) const;  //功能: 获得子字符串。  //参数说明:pos为起始位置(默认为0),n为结束位置(默认为npos)  //返回值: 子字符串

00
领券