c++如何切分字符串

   2024-09-30 3440
核心提示:在C++中,可以使用std::string类的成员函数substr和find来切分字符串。下面是一个简单的示例,展示了如何根据指定的分隔符来切分

在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函数来切分一个包含逗号分隔的字符串,并将结果打印到控制台。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号