首页 > 其他分享 >字符串转int

字符串转int

时间:2022-10-30 12:11:52浏览次数:55  
标签:radix int NumberFormatException result str 字符串 throw

将string类型转换成int型:

可以用integer类里面的valueof,但我们这里用parseint

String str="123";
Integer.parseInt(str);
Integer.parseInt(str,2);

其实对于valueof,其实他底层也是用的parseint来进行转换,因此我们来看一下parseint的底层代码看看他是怎么将字符类型转换成数据类型:

public static int parseInt(String s, int radix)
            throws NumberFormatException
{
    /*
     * WARNING: This method may be invoked early during VM initialization
     * before IntegerCache is initialized. Care must be taken to not use
     * the valueOf method.
     */

    if (s == null) {
        throw new NumberFormatException("null");
    }

    if (radix < Character.MIN_RADIX) {//最小2进制
        throw new NumberFormatException("radix " + radix +
                                        " less than Character.MIN_RADIX");
    }

    if (radix > Character.MAX_RADIX) {//最大36进制
        throw new NumberFormatException("radix " + radix +
                                        " greater than Character.MAX_RADIX");
    }

    int result = 0;
    boolean negative = false;//判断正负
    int i = 0, len = s.length();
    int limit = -Integer.MAX_VALUE;
    int multmin;
    int digit;

    if (len > 0) {
        char firstChar = s.charAt(0);
        if (firstChar < '0') { // Possible leading "+" or "-"
            if (firstChar == '-') {
                negative = true;
                limit = Integer.MIN_VALUE;
            } else if (firstChar != '+')
                throw NumberFormatException.forInputString(s);

            if (len == 1) // Cannot have lone "+" or "-"
                throw NumberFormatException.forInputString(s);
            i++;
        }
        multmin = limit / radix;
        while (i < len) {
            // Accumulating negatively avoids surprises near MAX_VALUE
            digit = Character.digit(s.charAt(i++),radix);
            if (digit < 0) {
                throw NumberFormatException.forInputString(s);
            }
            if (result < multmin) {
                throw NumberFormatException.forInputString(s);
            }
            result *= radix;
            if (result < limit + digit) {
                throw NumberFormatException.forInputString(s);
            }
            result -= digit;
        }
    } else {
        throw NumberFormatException.forInputString(s);
    }
    return negative ? result : -result;
}

写个方法来将string转换成十进制的数字:(肯定没有底层写的那么完美啦)

private static int toInt(String str,int radix) throws ParseException {
    Objects.nonNull(str);
    if(str=="")throw new NumberFormatException("str is null");
    int firstChar=str.charAt(0);
    boolean negative=false;
    int i=0;
    int len=str.length();
    if(firstChar<'0'){
        if(firstChar=='-')
            negative = true;
        else if(firstChar!='+')
        throw new NumberFormatException("input number is illegal");
        if(len==1)
        throw new NumberFormatException("str has illegal character");
    i++;
}
int num=0;
    while(i<len){
        int n=str.charAt(i++);
        if(n<'0'||n>'9')
            throw new NumberFormatException("middle num illegal");
        num=num*radix+(n-48);

    }
    return negative?-num:num;
}

没有考虑数值类型的范围2-32~231 ,因此超出范围可能还是有问题……

标签:radix,int,NumberFormatException,result,str,字符串,throw
From: https://www.cnblogs.com/Liku-java/p/16840922.html

相关文章

  • calico 报auto-detect an IPv4 address using interface regexes [ens18]: no valid h
    现象:.查看calicopod的时候报auto-detectanIPv4addressusinginterfaceregexes[ens18]:novalidhostinterfacesfound 分析:calico开启了ipvs地址自动检测......
  • Vue学习笔记之Vue判断字符串(或数组)中是否包含某个元素
    Vue判断包含0x00概述Vue判断​​字符串​​中是否包含某个字符串,有如下方法。 0x01includes方法(数组,字符串都可以)varstr=“HelloWorld!”......
  • Vue学习笔记之vue.js 两个等号 == 和三个等号===的区别 数字0和空字符串
    vuejavascript等号=====数字0空字符串/**==用于比较两者是否相等,忽略数据类型===用于更严谨的比较,值和值的数据类型都需要同时比较*/<!DOCT......
  • Java 使用StringBuilder组装字符串
    下面这个例子来自SpringBoot源码,这里是要打印程序启动的时间这样的字符串,需要拼装的信息有程序名字,启动时长,JVM时长。privateStringBuildergetStartedMessage(StopWatc......
  • 【XSY2499】字符串(AC自动机+树状数组)
    题面DescriptionUPD:本题字符集为全体小写字母InputOutputSampleInput51abc3abcabc0abc3aba1abababcSampleOutput22HINT题解这个“强制在......
  • 0090-Go-字符串
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/strings-and-runes目标使用Go语言的字符串。字节遍历packagemainimport"fmt"funcma......
  • 【LeeCode】字符串的全排列
    【题目描述】输入字符串str,返回str的字符的全排序【示例】输入:qwe输出:qweqewewqeqwwqeweq注意:如果输入的是n个相同的字符,那么也就只有1种排列组合【代码】list:保留......
  • js字符串转字节
    functionstringToByte(str){varlen,c;len=str.length;varbytes=[];for(vari=0;i<len;i++){c=str.charCodeAt(i);if(c>=0x010000&......
  • golang中的字符串
    0.1、索引​​https://waterflow.link/articles/1666449874974​​1、字符串编码在go中rune是一个unicode编码点。我们都知道UTF-8将字符编码为1-4个字节,比如我们常用的汉字......
  • 【LeeCode】字符串的排列
    【题目描述】给你两个字符串 ​​s1​​​ 和 ​​s2​​​ ,写一个函数来判断 ​​s2​​​ 是否包含 ​​s1​​ 的排列。如果是,返回 ​​true​​​ ;否则,返回 ......