È possibile convertire un array char[]
contenente numeri in e int
?Java char array to int
9
A
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;
}
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);
Problemi correlati
- 1. int array to BufferedImage
- 2. JAVA String to char
- 3. Efficienza: char array vs int array
- 4. Differenze tra int/char array/stringhe
- 5. Java - Change int to ascii
- 6. Java int ... notazione array
- 7. Stringa al char array Java
- 8. Mat to unsigned char *
- 9. Java ArrayList to Kotlin Array
- 10. Java: Slice Array To End
- 11. Oggetto Java to int: un modo migliore?
- 12. Char Array VS Char *
- 13. Cast struct to array?
- 14. KeyEventArgs.Key to char
- 15. Char to Operator C++
- 16. Convertire singolo char a int
- 17. Conversione char [,] array a char **
- 18. Allineamento dei char char array
- 19. 'main (int argc, char * argv [])'
- 20. Come usare "pointer to array 10 of int"?
- 21. Java: Casting Object to Array type
- 22. Java Serializable Object to Byte Array
- 23. UnicodeString to char * (UTF-8)
- 24. Percorso minimo labirinto Java 2d int array
- 25. Convert String a int array in Java
- 26. array int a json object in java
- 27. ArrayList di array int in java
- 28. Conversione del flusso di int in char in java
- 29. Perché è consentito assegnare char ad un int in java?
- 30. Lua string to int
Si può semplicemente sostituire il ciclo interno con 'risultato * = 10; '. –
Intendi sostituire 'digit * = 10; 'a' result * = 10; '? –
No, puoi eliminare l'intero * inner loop interno ('for (int j = ...') e sostituire tutte e tre le righe con solo 'result * = 10;'. –