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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Adobe Dreamweaver 2021下载安装教程

    Adobe Dreamweaver 2021下载安装教程软件介绍AdobeDreamweaver2021是专业的网站设计软件,使用可为处理各种Web文档提供灵活的环境。Dreamweaver2021一款非常受欢迎的网页设计软件,是该系列的全新版本,可以帮助广大学生、程序员制作出精美的网页,在全新的Dreamweaver2021版本中,在其优秀的功能上带来了更多的改进和优化,拥有无缝实时视图编辑功能,在以往用户需要切换到单独的编辑模式来预览网站,现在仅需一键即可预览和更改网页,还支持Windows的多显示器方案,为用户带来了更加整洁主界面,并且修改了十多个

    2022年7月14日
    23
  • python fillna函数_python中dropna函数

    python fillna函数_python中dropna函数我正在尝试在datetime64[ns]类型的列上运行fillna.当我运行类似的东西:DF[‘日期’].fillna(日期时间(“2000-01-01”))我明白了:TypeError:需要一个整数有什么方法吗?这应该在0.12和0.13(刚刚发布)中工作.@DSM指出日期时间的构造如下:datetime.datetime(2012,1,1)所以错误是由于未能构建您传递给fillna的值…

    2022年8月12日
    9
  • 对象转JSON首字母大写[通俗易懂]

    对象转JSON首字母大写[通俗易懂]最近在做一个第三方接口,接口给的数据类型如下请求报文如下{“A0144″:”12141256″,”AB6AM”:”中国银行支行”,”STATUS”:1}一般按照对象转JSON会使首字母小写,与接口文档不相符,因此需要转为大写,在字段名称前加@JSONField(name=””)注释即可如下:packagecn.com.cis.acic.util.personHr.vo.request;importcom.alibaba.fastjson.annotation.JS…

    2025年12月10日
    6
  • 贴片器件的识别[通俗易懂]

    贴片器件的识别[通俗易懂]前言实际板子上,贴片原件一般就较小,如果想知道贴片原件值,而且贴片件上有些标识.如果能辨别标识的含义,就不用将器件查下来量了。如果眼神不好(或者原件实在太小了),可以用工业显微镜拍下来,再识别原件上印刷的器件标识。在显微镜下,光滑好看的焊点,也变的那么粗糙:)慢慢记录,见到能用标识识别的器件,就记录一下。笔记0贴片电阻看到0R电阻电阻上画了一个小方框…

    2022年8月21日
    10
  • idea 2020 3.3 激活码_通用破解码

    idea 2020 3.3 激活码_通用破解码,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月16日
    436
  • MongoDB和MySQL和Redis的区别

    MongoDB和MySQL和Redis的区别MongoDB和MySQL和Redis的区别MySQL1、在不同的引擎上有不同的存储方式。2、查询语句是使用传统的sql语句,拥有较为成熟的体系,成熟度很高。3、开源数据库的份额在不断增加,mysql的份额页在持续增长。4、缺点就是在海量数据处理的时候效率会显著变慢。MongoDBMongodb是非关系型数据库(nosql),属于文档型数据库。文档是mongoDB中数据的基本单元,类似关系数据库的行,多个键值对有序地放置在一起便是文档,语法有点类似javascript面向对象的查询语言,

    2022年6月26日
    26

发表回复

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

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