java string类型转换成int类型(string怎么强转int)

String是引用类型,int是基本类型,所以两者的转换并不是基本类型间的转换,这也是该问题提出的意义所在,SUN公司提供了相应的类库供编程人员直接使用

大家好,又见面了,我是你们的朋友全栈君。

1.问题思考:

需要明确的是String是引用类型,int是基本类型,所以两者的转换并不是基本类型间的转换,这也是该问题提出的意义所在,SUN公司提供了相应的类库供编程人员直接使用。

2.Integer.parseInt(str) 与 Integer.valueOf(Str).intValue() :

其实查看Java源码不难发现后者的实现是基于parseInt函数来实现的,所以很有必要分析parseInt源码。

3.Integer.parseInt(str) 源码分析:

 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) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }

        if (radix > Character.MAX_RADIX) {
            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;
    }

加红源码如下:

public static int digit(char ch, int radix) {
        return digit((int)ch, radix);
    }
    /* @param   codePoint the character (Unicode code point) to be converted.
     * @param   radix   the radix.
     * @return  the numeric value represented by the character in the
     *          specified radix.
     * @see     Character#forDigit(int, int)
     * @see     Character#isDigit(int)
     * @since   1.5
     */
    public static int digit(int codePoint, int radix) {
        return CharacterData.of(codePoint).digit(codePoint, radix);
    }



可以看出加红代码是将字符 => Unicode(字符统一编码) =>  Unicode(数字统一编码) => 数字。

从上面的分析可以发现源码是取出字符串中的每个字符,然后将字符转换为数字进行拼接,但是在拼接的过程中SUN公司的编程人员是将其先拼接为负数,再用三元运算转换选择输出。自己并不认同,因为这样的做法是不利于理解,当然作者可能有自己的考虑,值得揣摩。

4.自己动手,丰衣足食:

  思路:

化整为零 ->  将引用类型的String分解为char;

逐个击破 ->  进本数据类型之间的转换Character.digit(ch,radix) / Character.getNumericValue(ch) 原理相同;

    由点及线-> 将数字放到不同权值得相应位置上,组成int型数值。

 注:

    正负号判断,数值长度判断,数字合法性校验(0-9)…

 CODEING:

public static int change(String s){
		int result = 0;     //数值
		int len = s.length(); 
		int indexEnd = len - 1;             //控制由右及左取字符(数字)
		int indexBegin = 0;     //起始位置(存在+ - 号)
		boolean negative = false;     //确定起始位置及输出结果标志符
		int position = 1;                   //权值:起始位置为个位
		int digit = 0;     //数字
		
	if(len > 0){
	    char firstChar = s.charAt(0);
            if (firstChar < '0') { 
                if (firstChar == '-') {
                    negative = true;
                    indexBegin = 1;
                }else if(firstChar == '+'){
                	indexBegin = 1;
                }else if (firstChar != '+'){
                	throw new NumberFormatException(s);
                } 
                if (len == 1) throw new NumberFormatException(s);
            }
            
            while (indexEnd >= indexBegin) {
            	//(int) s.charAt(indexEnd--);只是该字符的数字编码,十进制数字的Unicode码范围为48-57
            	if(s.charAt(indexEnd) < 48 || s.charAt(indexEnd)> 57){
            		throw new NumberFormatException(s);
            	}
                //int temp = Character.getNumericValue(s.charAt(indexEnd--));
                int temp = Character.digit(s.charAt(indexEnd--), 10);
                digit = temp * position;
                result += digit;
                position *= 10;
            }
		}
		return negative ? -result : result;
	}


5.C++的写法: 

handle four cases: – discards all leading whitespaces;- sign of the number;- overflow;- invalid input

int atoi(const char *str) {    int sign = 1, base = 0, i = 0;    while (str[i] == ' ') { i++; }    if (str[i] == '-' || str[i] == '+') {        sign = 1 - 2 * (str[i++] == '-'); //神一般的写法 或者 凡人 sign = str.charAt(i++) == '-' ? -1 : 1;    }    while (str[i] >= '0' && str[i] <= '9') {        if (base >  INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {            if (sign == 1) return INT_MAX;            else return INT_MIN;        }        base  = 10 * base + (str[i++] - '0');    }    return base * sign;}


6.学无止境,Java升级版:

public static int myAtoi(String str) {
	    int index = 0, sign = 1, total = 0;
	    //1. Empty string
	    if(str.length() == 0) return 0;

	    //2. Remove Spaces
	    while(str.charAt(index) == ' ' && index < str.length()) // str = str.trim();
	        index ++;

	    //3. Handle signs
	    if(str.charAt(index) == '+' || str.charAt(index) == '-'){
	        sign = str.charAt(index) == '+' ? 1 : -1;
	        index ++;
	    }
	    
	    //4. Convert number and avoid overflow
	    while(index < str.length()){
	        int digit = str.charAt(index) - '0';
	        if(digit < 0 || digit > 9) break;

	        //check if total will be overflow after 10 times and add digit
	        if(Integer.MAX_VALUE/10 < total || Integer.MAX_VALUE/10 == total && Integer.MAX_VALUE %10 < digit)
	            return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;

	        total = 10 * total + digit;
	        index ++;
	    }
	    return total * sign;
	}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/128955.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • nginx正向代理(超简单)

    正向代理是一个位于客户端和原始服务器之间的服务器,为了从原始服务器取得内容,客户端向代理发送一个请求并指定目标(原始服务器),然后代理向原始服务器转交请求并将获得的内容返回给客户端。环境192.168.153.179:正向代理192.168.153.178:客户端CentOSLinuxrelease7.5.1804(Core)关闭防火墙和selinux开始部署:首先,两台服务器安装nginx源码安装:1、安装启动安装依赖yum-yinstallwgetgcc

    2022年4月5日
    32
  • 马云口中的“计划经济” 其实是一种大数据和人工智能[通俗易懂]

    马云口中的“计划经济” 其实是一种大数据和人工智能

    2022年3月5日
    92
  • MySQL JDBC URL各参数详解

    MySQL JDBC URL各参数详解参数名称参数说明缺省值最低版本要求user数据库用户名(用于连接数据库)password用户密码(用于连接数据库)useUnicode是否使用Unicode字符集,如果参数characterEncoding设置为gb2312或gbk,本参数值必须设置为truefalse1.1guseSSLMySQL在高版本需要指明是否进行SSL连接在mysql连接字符串url中加入ssl=true或者false即可characterEncoding…

    2022年7月16日
    11
  • Java8使用Stream流实现List列表的查询、统计、排序、分组

    Java8使用Stream流实现List列表的查询、统计、排序、分组Java8提供了Stream(流)处理集合的关键抽象概念,它可以对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。StreamAPI借助于同样新出现的Lambda表达式,极大的提高编程效率和程序可读性。下面是使用Stream的常用方法的综合实例。(1)创建User.java(用户信息实体类)。importjava.math.BigDecimal;/***…

    2022年10月5日
    0
  • python win32api教程_解放双手——python win32api 入门「建议收藏」

    python win32api教程_解放双手——python win32api 入门「建议收藏」#_*_coding:UTF-8_*_”’本文在原程序的基础上做了修改补充,更加清晰易懂。get_mouse_point():返回当前鼠标的值(x,y)mouse_move(x,y):移动鼠标mouse_click(x,y):单击mouse_dclick(x,y):双击put(str=”,flag=0):flag默认为0,则表示输入的字符串,为1:字符要表示的是快捷组合按键,快捷键要用空…

    2022年10月11日
    0
  • 100vh和100%的区别[通俗易懂]

    100vh和100%的区别[通俗易懂]介绍vh就是当前屏幕可见高度的1%,也就是说height:100vh==height:100%;我的案例:元素没有设置高度的时候,我写移动端界面的时候用100vh会把屏幕撑大到需要滑动框,但是100%却不会。我是怎么解决的呢:在最外层包一个div,给这个div设置height:100vh…

    2022年5月4日
    67

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号