如何将逗号分隔的字符串元素放入int数组?

时间:2018-01-17 13:28:36

标签: c++ arrays string

这是一个例子:5,6,13,4,14,22 ,.  我想用5 6 13 4 12 22填充阵列 编译后返回:5 6,3 4,4,2。 当我介绍2,3,5,1,6,4时,数组将是正确的。

int nr=0;
    for(int j=0;j<sizeOfString;j++){
        if ((string[j] == ',')){
            output << j <<" j  ";//comma positions
        }else{
            stringArrayg[nr++]= putchar(string[j-2]);
        }
    }

2 个答案:

答案 0 :(得分:0)

以下是使用vectors,std :: replace和std :: istringstream:

的示例
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

std::vector<int> convertToIntArray(std::string input)
{
    std::replace(input.begin(), input.end(), ',', ' ');

    std::istringstream stringReader{ input };

    std::vector<int> result;

    int number;
    while (stringReader >> number)
    {
        result.push_back(number);
    }

    return result;
}

int main()
{
    std::string testString = "5,6,13,4,14,22";

    std::vector<int> newArray = convertToIntArray(testString);

    for (int i = 0; i < newArray.size(); ++i)
    {
        std::cout << newArray[i] << " ";
    }
}

答案 1 :(得分:0)

为什么不像这样使用Boost::Tokenizer

include <iostream>
#include <vector>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;
int main()
{
    string str = "5,6,13,4,14,22"; /// string to parse
    vector<int> nums; /// vector containing the numbers extracted from the string


    char_separator<char> sep(","); /// char separator for the tokenizer
    /// extracting all the tokens separated by ","
    tokenizer<char_separator<char> > tokens(str, sep); 

    /// looping over the tokes and storing them in the vector by
    /// casting each token to an int
    std::transform( tokens.begin(), tokens.end(), std::back_inserter(nums), &boost::lexical_cast<int,std::string> );

    /// printing the vector content
    for(const auto &v: nums) {
        cout << v << " ";
    }
    cout << endl;

    return 0;
}