【问题标题】:Split function doesn't work if there's two times the same character to split [closed]如果要拆分两次相同的字符,则拆分功能不起作用[关闭]
【发布时间】:2021-06-17 16:07:22
【问题描述】:

我正在做一个将字符串拆分为向量的程序(就像在 Python 中一样),我试图调试这段代码,但我不知道它有什么问题。

//split.hpp
#include <vector>

std::vector<std::string> split(std::string to_split, char split){
    std::vector<std::string> result;
    std::string append;
    for(int i = 0; i < to_split.length() ; ++i){
        if(to_split[i] == split){
            result.push_back(append);
            append.clear();
        }
        else append += to_split[i];
    }
    return result;
}

//main.cpp
#include <iostream>
#include "split.hpp"

int main(){
    std::vector<std::string> splitted_string = split("etettest", 't');
    for(int i = 0; i < splitted_string.size(); ++i){ 
        std::cout << splitted_string[i] << "\n";
    }
    std::cout << "\n" << splitted_string.size();
    system("pause>nul");
    return 0;
}

输入:e e tes

预期输入:e e es

【问题讨论】:

    标签: c++ string vector split


    【解决方案1】:

    运行您的代码,我得到了输入的预期输出(e e es):“etettest”。

    您忘记将最后一个块添加到结果数组中,因此最后一个拆分字符之后的任何内容都将被忽略。 "etettestend" 将产生与 "etettest" 相同的输出。

    【讨论】:

      猜你喜欢
      • 2014-03-05
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多