将字符串拆分为数组,数组中不需要的元素(似乎)

时间:2018-08-29 16:24:26

标签: c++ arrays string

我的代码可以很好地拆分,但是当我遍历并引用每个元素时,最后一个cout始终是未经修改的原始字符串。

例如:

SplitRowIntoArray("1,2,3");

将会输出:1 2 3 1,2,3

void SplitRowIntoArray(std::string row){

    std::string str = row;
    std::string strWords[24];
    short counter = 0;

    for(short i=0;i<str.length();i++){
        if(str[i] == ','){
            counter++;
        }
        else
        strWords[counter] += str[i];

    }

    for(int i = 0; i < sizeof(strWords); i++){
        std::cout << strWords[i] << std::endl;

    }
}  

1 个答案:

答案 0 :(得分:-1)

使用语言环境std::stringstreamstd::vector<std::string>

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>


struct comma_is_space : std::ctype<char>
{
    colon_is_space()
    : std::ctype<char>(get_table())
    {}

    static mask const* get_table()
    {
        static mask rc[table_size];
        rc[',']  = std::ctype_base::space;
        rc['\n'] = std::ctype_base::space;
        return rc;
    }
};

void SplitRowIntoArray(std::string row)
{
    std::stringstream ss{ row };
    ss.imbue(std::locale(ss.getloc(), new comma_is_space));

    std::vector<std::string> words{
        std::istream_iterator<std::string>{ss},
        std::istream_iterator<std::string>{}
    };

    for (auto const & word : words)
        std::cout << word << '\n';
}

int main()
{
    SplitRowIntoArray("1,2,3");
}