[SalesForce] Convert String to Integer Array

I have the following code:-

string clientNumber = '019224';
List<Integer> integerList = new List<Integer>();

How do I iterate through the clientNumber string as if it was an array and load each value into integerList to obtain the following values?

integerList[0] = 0
integerList[1] = 1
integerList[2] = 9
integerList[3] = 2
integerList[4] = 2
integerList[5] = 4

Best Answer

You can use String split in combination with Integer valueOf: Also, extra checks may be added to ensure that each character is valid digit (thanks to @Novarg)

String clientNumber = '019224';
List<Integer> integerList = new List<Integer>();

List<String> client_digits = clientNumber.split('');
for(String s : client_digits) {
    Integer parsed_digit = safeParse(s);
    if (s == null) {
        // invalid character. Do something with it
    } else {
        integerList.add(parsed_digit);
    }
}

//Static Utility method
public static Integer safeParse(String input) {
    Integer result = null;
    try {
        result = Integer.valueOf(input);
    } catch (Exception ex) {
        // Log here if there is generic logging utility
    }
    return result;
}
Related Topic