0

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.

0

4 Answers 4

4

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

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';
}

Comments

1

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;
}

Comments

0

Since Java 9 you can use String#codePoints method.

Try it online!

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]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.