涨见识!Java String转int还有这种写法
发布日期:2021-04-30 21:10:49 浏览次数:96 分类:精选文章

本文共 2084 字,大约阅读时间需要 6 分钟。

? Java ??String ? int ?????????????????????????????????????????????????123???????????+??????????????????????????

String a = "100";
String b = "50";
String c = a + b; // ????? "10050"

??????+???????????????+??????????????????????????????????????

  • Integer.valueOf()?

    String a = "100";
    String b = "50";
    int A = Integer.valueOf(a);
    int B = Integer.valueOf(b);
    int c = A + B; // ????? 150
  • Integer.parseInt()?

    String a = "100";
    String b = "50";
    int A = Integer.parseInt(a);
    int B = Integer.parseInt(b);
    int c = A + B; // ????? 150
  • ???Integer.parseInt() ???????????

    ?????????????????????????????????????

    public class String2IntDemo {
    public static void main(String[] args) {
    String a = "100";
    String b = "50";
    int A = string2int(a);
    int B = string2int(b);
    int c = A + B;
    System.out.println(c);
    }
    public static int string2int(String s) {
    int num = 0;
    int pos = 1;
    for (int i = s.length() - 1; i >= 0; i--) {
    num += (s.charAt(i) - '0') * pos;
    pos *= 10;
    }
    return num;
    }
    }

    ???????????????????????????????????????

    ????

  • ?????????? ???????-??????????????

  • ???????????? ??? NumberFormatException?

  • ??????? ????? 2???? 36?

  • ??

    Integer.parseInt() ??????????? Character.digit() ?????????????????

    ????

    public class S2IDemo {
    public static void main(String[] args) {
    String a = "-100";
    String b = "50";
    int A = string2int(a);
    int B = string2int(b);
    int c = A + B;
    System.out.println(c);
    }
    public static int string2int(String s) {
    boolean negative = false;
    char firstChar = s.charAt(0);
    if (firstChar == '-') {
    negative = true;
    s = s.substring(1);
    }
    int num = 0;
    int pos = 1;
    for (int i = s.length() - 1; i >= 0; i--) {
    num += (s.charAt(i) - '0') * pos;
    pos *= 10;
    }
    return negative ? -num : num;
    }
    }

    ??

    ????? string2int() ????????????? Integer.parseInt() ????????????????????????????????????????

    上一篇:关于春招、BAT大厂的职场文化、薪资与八卦,pick一下?
    下一篇:跳槽加薪总会比内部调薪要高,金三银四整装待发...你的技术我来买单!

    发表评论

    最新留言

    不错!
    [***.144.177.141]2026年06月22日 12时27分14秒