Is it possible to convert a char[]
array containing numbers into
an int
?
We can use the parseInt() method and valueOf() method to convert char array to int in Java. The parseInt() method takes a String object which is returned by the valueOf() method, and returns an integer value. This method belongs to the Integer class so that it can be used for conversion into an integer.
char[] arr = { 'p', 'q', 'r', 's' }; The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With