最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】android中的java中的string转int

Android crifan 5356浏览 0评论

【问题】

需要将一个字符串,可能是十进制:

比如

123

也可能是16进制:

0x123

转换为int值。

【折腾过程】

1.参考:

How to convert string to int in Java?

去试试,

	void strToIntTest(){
		String testStr1 = "123";
		String testStr2 = "0x123";
		
		int convertedIntValue1 = Integer.parseInt(testStr1);
		int convertedIntValue2 = Integer.parseInt(testStr2);
		System.out.println("convertedIntValue1=" + convertedIntValue1 + ", convertedIntValue2=" + convertedIntValue2);
	}

应该就可以了。

结果调试发现:

int convertedIntValue2 = Integer.parseInt(testStr2);

会挂掉。

2.然后自己去试试,通过自带文档,发现有个decode:

interger decode can parse 0x hex string to int

然后去试试:

	void strToIntTest(){
		String testStr1 = "123";
		String testStr2 = "0x456";
		
		int convertedIntValue1 = Integer.parseInt(testStr1);
		//int convertedIntValue2 = Integer.parseInt(testStr2);
		int convertedIntValue2 = Integer.decode(testStr2);
		
		System.out.println("convertedIntValue1=" + convertedIntValue1 + ", convertedIntValue2=" + convertedIntValue2);
	}

结果,虽然工作了。

却又遇到:

【已解决】android中使用System.out.println结果不工作:无法在ADT的LogCat或console中看到输出结果

 

【总结】

直接调用

Integer.parseInt

即可将string转为int,但是不支持0x123的形式。

最后去用:

Integer.decode("0x123");

才可以。

转载请注明:在路上 » 【已解决】android中的java中的string转int

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.254 seconds, using 22.07MB memory