Java String to Int Array convertStringToIntArray(String data)

Here you can find the source of convertStringToIntArray(String data)

Description

Produces and int array from a String containing comma-separated values

License

Open Source License

Parameter

Parameter Description
data A String containing comma-separated values, eg: "-1, 7, 2", "-1,7,2", "-1", ""

Return

{-1, 7, 2}, {-1, 7, 2}, {-1}, {}

Declaration

public static int[] convertStringToIntArray(String data) 

Method Source Code

//package com.java2s;
/*//  w  w w .  j av a  2s.  co m
 * Copyright (c) 2009, SQL Power Group Inc.
 *
 * This file is part of SQL Power Library.
 *
 * SQL Power Library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SQL Power Library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

public class Main {
    /**
     * Produces and int array from a String containing comma-separated values
     * @param data A String containing comma-separated values, eg: "-1, 7, 2", "-1,7,2", "-1", ""
     * @return {-1, 7, 2}, {-1, 7, 2}, {-1}, {}
     */
    public static int[] convertStringToIntArray(String data) {
        String[] s = data.split(",");
        int[] ints = new int[s.length];
        for (int i = 0; i < s.length; i++) {
            try {
                ints[i] = Integer.parseInt(s[i]);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException(e);
            }
        }
        return ints;
    }
}

Related

  1. convertStringToIntegerArray(String string)