如何将char数组转换为int数组?

时间:2014-03-14 06:11:40

标签: java

假设我正在使用此代码将String(包含数字)转换为字符数组,我想将其转换为数字数组(int)。

(然后我想为另一个数字字符串执行此操作,并添加两个int数组以提供另外一个添加的int数组。)

我该怎么办?

import java.util.Scanner;


public class stringHundredDigitArray {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number: ");
        String num1 = in.nextLine();
        char[] num1CharArray = num1.toCharArray();
        //for (int i = 0; i < num1CharArray.length; i++){
            //System.out.print(" "+num1CharArray[i]);
        //}

        int[] num1intarray = new int[num1CharArray.length];
        for (int i = 0; i < num1CharArray.length; i++){
            num1intarray[i] = num1CharArray[i];
        }

        for (int i = 0; i < num1intarray.length; i++){ //this code prints presumably the ascii values of the number characters, not the numbers themselves. This is the problem.
            System.out.print(" "+num1intarray[i]);
        }
    }

}

我真的必须拆分字符串,最好是一组可添加的数据类型。

3 个答案:

答案 0 :(得分:2)

尝试Character.getNumericValue(char);这个:

for (int i = 0; i < num1CharArray.length; i++){
    num1intarray[i] = Character.getNumericValue(num1CharArray[i]);
}

答案 1 :(得分:1)

Try This :
     int[] num1intarray = new int[num1CharArray.length];
    for (int i = 0; i < num1CharArray.length; i++)
        {
         num1intarray[i]=Integer.parseInt(""+num1CharArray[i]);
        System.out.print(num1intarray[i]); 
       }

答案 2 :(得分:0)

简短而简单的解决方案!

int[] result = new int[charArray.length]; 
Arrays.setAll(result, i -> Character.getNumericValue(charArray[i]));