Java String to Int Array convertStringToIntegerArray(String string)

Here you can find the source of convertStringToIntegerArray(String string)

Description

Takes a string and takes each possible number and stores them in an int array

License

Creative Commons License

Parameter

Parameter Description
string a parameter

Declaration

public static int[] convertStringToIntegerArray(String string) 

Method Source Code

//package com.java2s;
//License from project: Creative Commons License 

public class Main {
    /**/*from w w  w .  j  a v  a  2  s  .c  o  m*/
     * Takes a string and takes each possible number and stores them in an int array
     * @param string
     * @return
     */
    public static int[] convertStringToIntegerArray(String string) {
        int[] numbers = new int[string.length()];
        for (int i = 0; i < string.length(); ++i) {
            String substring = string.substring(i, i + 1);
            if (isValid(substring))
                numbers[i] = Integer.parseInt(substring);
        }
        return numbers;
    }

    /**
     * Checks to see if a string represents a valid number
     * @param string a string value that could potentially represents a number
     * @return a boolean indicating if the string actually represented a number
     */
    public static boolean isValid(String string) {
        try {
            Float aFloat = Float.valueOf(string);
            assert aFloat != null;
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}

Related

  1. convertStringToIntArray(String data)