Java: analizar el valor int de un char


Sólo quiero saber si hay una mejor solución para analizar un número de un carácter en una cadena (suponiendo que sabemos que el carácter en el índice n es un número).

String element = "el5";
String s;
s = ""+element.charAt(2);
int x = Integer.parseInt(s);

//result: x = 5

(inútil decir que es solo un ejemplo)

Author: Noya, 2011-02-11

5 answers

Intente Character.getNumericValue(char).

String element = "el5";
int x = Character.getNumericValue(element.charAt(2));
System.out.println("x=" + x);

Produce:

x=5

Lo bueno de getNumericValue(char) es que también funciona con cadenas como "el٥" y "el५" donde ٥ y son los dígitos 5 en árabe oriental e Hindi/sánscrito respectivamente.

 382
Author: Bart Kiers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-30 04:24:14

Intente lo siguiente:

str1="2345";
int x=str1.charAt(2)-'0';
//here x=4;

Si u resta por char '0', el valor ASCII no necesita ser conocido.

 52
Author: vashishatashu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-31 01:06:07

Eso es probablemente lo mejor desde el punto de vista del rendimiento, pero es áspero:

String element = "el5";
String s;
int x = element.charAt(2)-'0';

Funciona si asumes que tu carácter es un dígito, y solo en idiomas siempre usando Unicode, como Java...

 28
Author: Alexis Dufrenoy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-12 20:46:46

Simplemente restando por char '0'(cero) un char (de dígito '0' a '9') se puede convertir en int(0 a 9), por ejemplo, '5'-'0' da int 5.

String str = "123";

int a=str.charAt(1)-'0';
 16
Author: Miniraj Shrivastava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-24 21:49:09
String a = "jklmn489pjro635ops";

int sum = 0;

String num = "";

boolean notFirst = false;

for (char c : a.toCharArray()) {

    if (Character.isDigit(c)) {
        sum = sum + Character.getNumericValue(c);
        System.out.print((notFirst? " + " : "") + c);
        notFirst = true;
    }
}

System.out.println(" = " + sum);
 6
Author: John McDonald,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-20 03:00:03