String 与 int 类型之间的互相转换_string int-程序员宅基地

技术标签: java基础  


1 如何将字串 String 转换成整数 int?

A. 有两个方法:

1). int i = Integer.parseInt([String]); 或

i = Integer.parseInt([String],[int radix]);

2). int i = Integer.valueOf(my_str).intValue();

注: 字串转成 Double, Float, Long 的方法大同小异.

2 如何将整数 int 转换成字串 String ?

A. 有叁种方法:

1.) String s = String.valueOf(i);

2.) String s = Integer.toString(i);

3.) String s = "" + i;

注: Double, Float, Long 转成字串的方法大同小异.

 

int -> String 

int i=12345;
String s="";
第一种方法:s=i+"";
第二种方法:s=String.valueOf(i);
这两种方法有什么区别呢?作用是不是一样的呢?是不是在任何下都能互换呢?

String -> int 

s="12345";
int i;
第一种方法:i=Integer.parseInt(s);
第二种方法:i=Integer.valueOf(s).intValue();
这两种方法有什么区别呢?作用是不是一样的呢?是不是在任何下都能互换呢?

以下是答案:

第一种方法:s=i+""; //会产生两个String对象
第二种方法:s=String.valueOf(i); //直接使用String类的静态方法,只产生一个对象

第一种方法:i=Integer.parseInt(s);//直接使用静态方法,不会产生多余的对象,但会抛出异常
第二种方法:i=Integer.valueOf(s).intValue();//Integer.valueOf(s) 相当于 new Integer(Integer.parseInt(s)),也会抛

异常,但会多产生一个对象


1.问题思考:

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

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

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

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

[java]  view plain  copy
  1. public static int parseInt(String s, int radix)  
  2.                throws NumberFormatException  
  3.    {  
  4.        /* 
  5.         * WARNING: This method may be invoked early during VM initialization 
  6.         * before IntegerCache is initialized. Care must be taken to not use 
  7.         * the valueOf method. 
  8.         */  
  9.   
  10.        if (s == null) {  
  11.            throw new NumberFormatException("null");  
  12.        }  
  13.   
  14.        if (radix < Character.MIN_RADIX) {  
  15.            throw new NumberFormatException("radix " + radix +  
  16.                                            " less than Character.MIN_RADIX");  
  17.        }  
  18.   
  19.        if (radix > Character.MAX_RADIX) {  
  20.            throw new NumberFormatException("radix " + radix +  
  21.                                            " greater than Character.MAX_RADIX");  
  22.        }  
  23.   
  24.        int result = 0;  
  25.        boolean negative = false;  
  26.        int i = 0, len = s.length();  
  27.        int limit = -Integer.MAX_VALUE;  
  28.        int multmin;  
  29.        int digit;  
  30.   
  31.        if (len > 0) {  
  32.            char firstChar = s.charAt(0);  
  33.            if (firstChar < '0') { // Possible leading "+" or "-"  
  34.                if (firstChar == '-') {  
  35.                    negative = true;  
  36.                    limit = Integer.MIN_VALUE;  
  37.                } else if (firstChar != '+')  
  38.                    throw NumberFormatException.forInputString(s);  
  39.   
  40.                if (len == 1// Cannot have lone "+" or "-"  
  41.                    throw NumberFormatException.forInputString(s);  
  42.                i++;  
  43.            }  
  44.            multmin = limit / radix;  
  45.            while (i < len) {  
  46.                // Accumulating negatively avoids surprises near MAX_VALUE  
  47.                <span style="color:#ff0000;">digit = Character.digit(s.charAt(i++),radix);</span>  
  48.                if (digit < 0) {  
  49.                    throw NumberFormatException.forInputString(s);  
  50.                }  
  51.                if (result < multmin) {  
  52.                    throw NumberFormatException.forInputString(s);  
  53.                }  
  54.                result *= radix;  
  55.                if (result < limit + digit) {  
  56.                    throw NumberFormatException.forInputString(s);  
  57.                }  
  58.                result -= digit;  
  59.            }  
  60.        } else {  
  61.            throw NumberFormatException.forInputString(s);  
  62.        }  
  63.        return negative ? result : -result;  
  64.    }  

加红源码如下:

[java]  view plain  copy
  1. public static int digit(char ch, int radix) {  
  2.         return digit((int)ch, radix);  
  3.     }  
[html]  view plain  copy
  1. /* @param   codePoint the character (Unicode code point) to be converted.  
  2.  * @param   radix   the radix.  
  3.  * @return  the numeric value represented by the character in the  
  4.  *          specified radix.  
  5.  * @see     Character#forDigit(int, int)  
  6.  * @see     Character#isDigit(int)  
  7.  * @since   1.5  
  8.  */  
  9. public static int digit(int codePoint, int radix) {  
  10.     return CharacterData.of(codePoint).digit(codePoint, radix);  
  11. }  

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

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

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

  思路:

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

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

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

 注:

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

 CODEING:

[java]  view plain  copy
  1. public static int change(String s){  
  2.         int result = 0;<span style="white-space:pre;">          </span>    //数值  
  3.         int len = s.length();<span style="white-space:pre;">        </span>  
  4.         int indexEnd = len - 1;             //控制由右及左取字符(数字)  
  5.         int indexBegin = 0;<span style="white-space:pre;">      </span>    //起始位置(存在+ - 号)  
  6.         boolean negative = false;<span style="white-space:pre;">    </span>    //确定起始位置及输出结果标志符  
  7.         int position = 1;                   //权值:起始位置为个位  
  8.         int digit = 0;<span style="white-space:pre;">           </span>    //数字  
  9.           
  10.     if(len > 0){  
  11.         char firstChar = s.charAt(0);  
  12.             if (firstChar < '0') {   
  13.                 if (firstChar == '-') {  
  14.                     negative = true;  
  15.                     indexBegin = 1;  
  16.                 }else if(firstChar == '+'){  
  17.                     indexBegin = 1;  
  18.                 }else if (firstChar != '+'){  
  19.                     throw new NumberFormatException(s);  
  20.                 }   
  21.                 if (len == 1throw new NumberFormatException(s);  
  22.             }  
  23.               
  24.             while (indexEnd >= indexBegin) {  
  25.                 //(int) s.charAt(indexEnd--);只是该字符的数字编码,十进制数字的Unicode码范围为48-57  
  26.                 if(s.charAt(indexEnd) < 48 || s.charAt(indexEnd)> 57){  
  27.                     throw new NumberFormatException(s);  
  28.                 }  
  29.                 //int temp = Character.getNumericValue(s.charAt(indexEnd--));  
  30.                 int temp = Character.digit(s.charAt(indexEnd--), 10);  
  31.                 digit = temp * position;  
  32.                 result += digit;  
  33.                 position *= 10;  
  34.             }  
  35.         }  
  36.         return negative ? -result : result;  
  37.     }  


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

[java]  view plain  copy
  1. public static int myAtoi(String str) {  
  2.         int index = 0, sign = 1, total = 0;  
  3.         //1. Empty string  
  4.         if(str.length() == 0return 0;  
  5.   
  6.         //2. Remove Spaces  
  7.         while(str.charAt(index) == ' ' && index < str.length()) // str = str.trim();  
  8.             index ++;  
  9.   
  10.         //3. Handle signs  
  11.         if(str.charAt(index) == '+' || str.charAt(index) == '-'){  
  12.             sign = str.charAt(index) == '+' ? 1 : -1;  
  13.             index ++;  
  14.         }  
  15.           
  16.         //4. Convert number and avoid overflow  
  17.         while(index < str.length()){  
  18.             int digit = str.charAt(index) - '0';  
  19.             if(digit < 0 || digit > 9break;  
  20.   
  21.             //check if total will be overflow after 10 times and add digit  
  22.             if(Integer.MAX_VALUE/10 < total || Integer.MAX_VALUE/10 == total && Integer.MAX_VALUE %10 < digit)  
  23.                 return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;  
  24.   
  25.             total = 10 * total + digit;  
  26.             index ++;  
  27.         }  
  28.         return total * sign;  
  29.     }  

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/rui_xiao/article/details/79711950

智能推荐

JWT(Json Web Token)实现无状态登录_无状态token登录-程序员宅基地

文章浏览阅读685次。1.1.什么是有状态?有状态服务,即服务端需要记录每次会话的客户端信息,从而识别客户端身份,根据用户身份进行请求的处理,典型的设计如tomcat中的session。例如登录:用户登录后,我们把登录者的信息保存在服务端session中,并且给用户一个cookie值,记录对应的session。然后下次请求,用户携带cookie值来,我们就能识别到对应session,从而找到用户的信息。缺点是什么?服务端保存大量数据,增加服务端压力 服务端保存用户状态,无法进行水平扩展 客户端请求依赖服务.._无状态token登录

SDUT OJ逆置正整数-程序员宅基地

文章浏览阅读293次。SDUT OnlineJudge#include<iostream>using namespace std;int main(){int a,b,c,d;cin>>a;b=a%10;c=a/10%10;d=a/100%10;int key[3];key[0]=b;key[1]=c;key[2]=d;for(int i = 0;i<3;i++){ if(key[i]!=0) { cout<<key[i.

年终奖盲区_年终奖盲区表-程序员宅基地

文章浏览阅读2.2k次。年终奖采用的平均每月的收入来评定缴税级数的,速算扣除数也按照月份计算出来,但是最终减去的也是一个月的速算扣除数。为什么这么做呢,这样的收的税更多啊,年终也是一个月的收入,凭什么减去12*速算扣除数了?这个霸道(不要脸)的说法,我们只能合理避免的这些跨级的区域了,那具体是那些区域呢?可以参考下面的表格:年终奖一列标红的一对便是盲区的上下线,发放年终奖的数额一定一定要避免这个区域,不然公司多花了钱..._年终奖盲区表

matlab 提取struct结构体中某个字段所有变量的值_matlab读取struct类型数据中的值-程序员宅基地

文章浏览阅读7.5k次,点赞5次,收藏19次。matlab结构体struct字段变量值提取_matlab读取struct类型数据中的值

Android fragment的用法_android reader fragment-程序员宅基地

文章浏览阅读4.8k次。1,什么情况下使用fragment通常用来作为一个activity的用户界面的一部分例如, 一个新闻应用可以在屏幕左侧使用一个fragment来展示一个文章的列表,然后在屏幕右侧使用另一个fragment来展示一篇文章 – 2个fragment并排显示在相同的一个activity中,并且每一个fragment拥有它自己的一套生命周期回调方法,并且处理它们自己的用户输_android reader fragment

FFT of waveIn audio signals-程序员宅基地

文章浏览阅读2.8k次。FFT of waveIn audio signalsBy Aqiruse An article on using the Fast Fourier Transform on audio signals. IntroductionThe Fast Fourier Transform (FFT) allows users to view the spectrum content of _fft of wavein audio signals

随便推点

Awesome Mac:收集的非常全面好用的Mac应用程序、软件以及工具_awesomemac-程序员宅基地

文章浏览阅读5.9k次。https://jaywcjlove.github.io/awesome-mac/ 这个仓库主要是收集非常好用的Mac应用程序、软件以及工具,主要面向开发者和设计师。有这个想法是因为我最近发了一篇较为火爆的涨粉儿微信公众号文章《工具武装的前端开发工程师》,于是建了这么一个仓库,持续更新作为补充,搜集更多好用的软件工具。请Star、Pull Request或者使劲搓它 issu_awesomemac

java前端技术---jquery基础详解_简介java中jquery技术-程序员宅基地

文章浏览阅读616次。一.jquery简介 jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTML documents、events、实现动画效果,并且方便地为网站提供AJAX交互 jQuery 的功能概括1、html 的元素选取2、html的元素操作3、html dom遍历和修改4、js特效和动画效果5、css操作6、html事件操作7、ajax_简介java中jquery技术

Ant Design Table换滚动条的样式_ant design ::-webkit-scrollbar-corner-程序员宅基地

文章浏览阅读1.6w次,点赞5次,收藏19次。我修改的是表格的固定列滚动而产生的滚动条引用Table的组件的css文件中加入下面的样式:.ant-table-body{ &amp;amp;::-webkit-scrollbar { height: 5px; } &amp;amp;::-webkit-scrollbar-thumb { border-radius: 5px; -webkit-box..._ant design ::-webkit-scrollbar-corner

javaWeb毕设分享 健身俱乐部会员管理系统【源码+论文】-程序员宅基地

文章浏览阅读269次。基于JSP的健身俱乐部会员管理系统项目分享:见文末!

论文开题报告怎么写?_开题报告研究难点-程序员宅基地

文章浏览阅读1.8k次,点赞2次,收藏15次。同学们,是不是又到了一年一度写开题报告的时候呀?是不是还在为不知道论文的开题报告怎么写而苦恼?Take it easy!我带着倾尽我所有开题报告写作经验总结出来的最强保姆级开题报告解说来啦,一定让你脱胎换骨,顺利拿下开题报告这个高塔,你确定还不赶快点赞收藏学起来吗?_开题报告研究难点

原生JS 与 VUE获取父级、子级、兄弟节点的方法 及一些DOM对象的获取_获取子节点的路径 vue-程序员宅基地

文章浏览阅读6k次,点赞4次,收藏17次。原生先获取对象var a = document.getElementById("dom");vue先添加ref <div class="" ref="divBox">获取对象let a = this.$refs.divBox获取父、子、兄弟节点方法var b = a.childNodes; 获取a的全部子节点 var c = a.parentNode; 获取a的父节点var d = a.nextSbiling; 获取a的下一个兄弟节点 var e = a.previ_获取子节点的路径 vue