Java: parse int value from a char

后端 未结 7 1162
借酒劲吻你
借酒劲吻你 2020-11-22 16:10

I just want to know if there\'s a better solution to parse a number from a character in a string (assuming that we know that the character at index n is a number).



        
相关标签:
7条回答
  • 2020-11-22 16:33

    Try the following:

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

    if u subtract by char '0', the ASCII value needs not to be known.

    0 讨论(0)
  • 2020-11-22 16:43
    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);
    
    0 讨论(0)
  • 2020-11-22 16:44

    That's probably the best from the performance point of view, but it's rough:

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

    It works if you assume your character is a digit, and only in languages always using Unicode, like Java...

    0 讨论(0)
  • 2020-11-22 16:45

    Try Character.getNumericValue(char).

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

    produces:

    x=5
    

    The nice thing about getNumericValue(char) is that it also works with strings like "el٥" and "el५" where ٥ and are the digits 5 in Eastern Arabic and Hindi/Sanskrit respectively.

    0 讨论(0)
  • 2020-11-22 16:50
    String element = "el5";
    int x = element.charAt(2) - 48;
    

    Subtracting ascii value of '0' = 48 from char

    0 讨论(0)
  • 2020-11-22 16:53

    By simply subtracting by char '0'(zero) a char (of digit '0' to '9') can be converted into int(0 to 9), e.g., '5'-'0' gives int 5.

    String str = "123";
    
    int a=str.charAt(1)-'0';
    
    0 讨论(0)
提交回复
热议问题