Reputation: 43
I have a string like, "12345"
and want to convert it to the integer array, {1,2,3,4,5}
.
I want one method to convert a character to an integer, '1' -> 1
. And another method to create the array.
This is what I have so far:
public static int charToInt(char character) {
int newInt;
newInt = (int) character;
return newInt;
}
public static int[] convertStringToIntArray(String keyString) {
int keyLength = keyString.length();
int element;
int[] intArray = new int[keyLength];
for (element = 0; element < keyLength; element++) {
intArray[element] = charToInt(keyString.charAt(element));
}
// return
return intArray;
}
I think the problem is in the charToInt
method. I think it is converting the char
to its ascii value. But I am not sure if the other method is right either.
Any help would be greatly appreciated.
Upvotes: 0
Views: 184
Reputation:
Since Java 9 you can use String#codePoints
method.
public static int[] convertStringToIntArray(String keyString) {
return keyString.codePoints().map(Character::getNumericValue).toArray();
}
public static void main(String[] args) {
String str = "12345";
int[] arr = convertStringToIntArray(str);
// output
System.out.println(Arrays.toString(arr));
// [1, 2, 3, 4, 5]
}
Upvotes: 0
Reputation: 189
This might help -
int keyLength = keyString.length();
int num = Integer.parseInt(keyString);
int[] intArray = new int[ keyLength ];
for(int i=keyLength-1; i>=0; i--){
intArray[i] = num % 10;
num = num / 10;
}
Upvotes: 1
Reputation: 19545
Since Java 1.5 Character
has an interesting method getNumericValue
which allows to convert char digits to int values.
So with the help of Stream API, the entire method convertStringToIntArray
may be rewritten as:
public static int[] convertStringToIntArray(String keyString) {
Objects.requireNonNull(keyString);
return keyString.chars().map(Character::getNumericValue).toArray();
}
Upvotes: 4
Reputation: 27205
You are right. The problem here is in charToInt
.
(int) character
is just the ascii codepoint (or rather UTF-16 codepoint).
Because the digits '0'
to '9'
have increasing codepoints you can convert any digit into a number by subtracting '0'
.
public static int charToInt(char digit)
{
return digit - '0';
}
Upvotes: 1