Java: parse int value from a char

Chcę tylko wiedzieć, czy jest lepsze rozwiązanie do parsowania liczby ze znaku w łańcuchu (zakładając, że wiemy, że znak w indeksie n jest liczbą).

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

//result: x = 5

(nie warto mówić, że to tylko przykład)

Author: Noya, 2011-02-11

5 answers

Spróbuj Character.getNumericValue(char).

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

Produkuje:

x=5

Fajną rzeczą w getNumericValue(char) jest to, że działa również z ciągami takimi jak "el٥" i "el५" Gdzie ٥ i są cyframi 5 W odpowiednio wschodnim arabskim i Hindi/sanskrycie.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-30 04:24:14

Spróbuj:

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

Jeśli u odjąć przez znak '0', wartość ASCII nie musi być znana.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-31 01:06:07

To chyba najlepsze z punktu widzenia wydajności, ale jest szorstkie:

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

Działa, jeśli założysz, że twój znak jest cyfrą i tylko w językach zawsze używających Unicode, takich jak 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-12 20:46:46

Po prostu odejmując znak ' 0 '(zero) znak(cyfry' 0 'do' 9') może być zamieniony na int (0 do 9), np.'5'-' 0 ' daje 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/doraprojects.net/template/agent.layouts/content.php on line 54
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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-20 03:00:03