开发者

Java char array to int

Is开发者_如何学C it possible to convert a char[] array containing numbers into an int?


Does the char[] contain the unicode characters making up the digits of the number? In that case simply create a String from the char[] and use Integer.parseInt:

char[] digits = { '1', '2', '3' };
int number = Integer.parseInt(new String(digits));


Even more performance and cleaner code (and no need to allocate a new String object):

int charArrayToInt(char []data,int start,int end) throws NumberFormatException
{
    int result = 0;
    for (int i = start; i < end; i++)
    {
        int digit = (int)data[i] - (int)'0';
        if ((digit < 0) || (digit > 9)) throw new NumberFormatException();
        result *= 10;
        result += digit;
    }
    return result;
}


char[] digits = { '0', '1', '2' };
int number = Integer.parseInt(String.valueOf(digits));

This also works.


It is possible to convert a char[] array containing numbers into an int. You can use following different implementation to convert array.

  1. Using Integer.parseInt

    public static int charArrayToInteger(char[] array){
        String arr = new String(array);
        int number = Integer.parseInt(arr);
    
        return number;
    }
    
  2. Without Integer.parseInt

    public static int charArrayToInt(char[] array){
        int result = 0;
        int length = array.length - 1;
    
        for (int i = 0; i <= length; i++)
        {
             int digit = array[i] - '0'; //we don't want to cast by using (int)
             result *= 10;
             result += digit;
        }
        return result;
    }
    

Example:

 public static void main(String []args){
    char[] array = {'1', '2', '3', '4', '5'};
    int result = 0;

    result = charArrayToInteger(array);
    System.out.println("Using Integer.parseInt: " + result);

    result = charArrayToInt(array);
    System.out.println("Without Integer.parseInt: " + result);

 }

Output:

Using Integer.parseInt: 12345
Without Integer.parseInt: 12345


Another way with more performance:

char[] digits = { '1', '2', '3' };

int result = 0;
for (int i = 0; i < chars.length; i++) {
   int digit = ((int)chars[i] & 0xF);
   for (int j = 0; j < chars.length-1-i; j++) {
        digit *= 10;
   }
   result += digit;
}


Well, you can try even this

    char c[] = {'1','2','3'};
    int total=0,x=0,m=1;
    for(int i=c.length-1;i>=0;i--)
    {
        x = c[i] - '0';
        x = x*m;
        m *= 10;
        total += x;
    }
    System.out.println("Integer is " + total);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜