首页主机资讯c++如何切分字符串

c++如何切分字符串

时间2024-09-05 23:32:03发布访客分类主机资讯浏览1166
导读:在C++中,可以使用std::string类的成员函数substr和find来切分字符串。下面是一个简单的示例,展示了如何根据指定的分隔符来切分字符串: #include<iostream> #include<vector...

在C++中,可以使用std::string类的成员函数substrfind来切分字符串。下面是一个简单的示例,展示了如何根据指定的分隔符来切分字符串:

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

std::vector<
    std::string>
     split(const std::string&
 input, char delimiter) {
    
    std::vector<
    std::string>
     result;
    
    std::size_t startPos = 0;
    
    std::size_t endPos = input.find(delimiter);


    while (endPos != std::string::npos) {
    
        result.push_back(input.substr(startPos, endPos - startPos));
    
        startPos = endPos + 1;
    
        endPos = input.find(delimiter, startPos);

    }
    

    result.push_back(input.substr(startPos));
    
    return result;

}


int main() {
    
    std::string input = "Hello,World,This,Is,A,Test";
    
    char delimiter = ',';
    

    std::vector<
    std::string>
     tokens = split(input, delimiter);
    

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

    }
    

    return 0;

}
    

在这个示例中,我们定义了一个名为split的函数,它接受一个输入字符串和一个分隔符作为参数。函数首先创建一个空的std::vector< std::string> 对象来存储切分后的子字符串。然后,它使用find函数查找分隔符在输入字符串中的位置,并使用substr函数从输入字符串中提取子字符串。最后,将提取到的子字符串添加到结果向量中。当find函数返回std::string::npos时,表示已经找不到更多的分隔符,此时函数将剩余的子字符串添加到结果向量中并返回。

main函数中,我们调用split函数来切分一个包含逗号分隔的字符串,并将结果打印到控制台。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: c++如何切分字符串
本文地址: https://pptw.com/jishu/697702.html
工程项目如何支付进度款 如何找研发项目进度表格

游客 回复需填写必要信息