2010-04-21 17 views

risposta

16

Il char[] contiene i caratteri unicode che costituiscono le cifre del numero? In tal caso, è sufficiente creare una stringa dal char[] e utilizzare Integer.parseInt:

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

Un altro modo con maggiori prestazioni:

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

Si può semplicemente sostituire il ciclo interno con 'risultato * = 10; '. –

+0

Intendi sostituire 'digit * = 10; 'a' result * = 10; '? –

+1

No, puoi eliminare l'intero * inner loop interno ('for (int j = ...') e sostituire tutte e tre le righe con solo 'result * = 10;'. –

10

Ancora più prestazioni e codice più pulito (e non c'è bisogno di allocare una nuova oggetto String):

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; 
} 
6
char[] digits = { '0', '1', '2' }; 
int number = Integer.parseInt(String.valueOf(digits)); 

funziona in questo anche.

0

È possibile utilizzare in questo modo per ottenere uno ad uno per int

char[] chars = { '0', '1', '2' }; 
int y=0; 
for (int i = 0; i < chars.length; i++) { 
    y = Integer.parseInt(String.valueOf(chars[i])); 
    System.out.println(y); 
} 
0

Beh, si può provare anche questo

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