Java中字符(串)和数值类型的转换

本文详细介绍了字符串转数值(Integer.parseInt),字符转数值(char to int),数值转字符串(String.valueOf和Integer.toString),以及字符串中特定子串定位的方法。通过实例展示了如何处理字符数组,提取整数,并找到特定子串的位置。
摘要由CSDN通过智能技术生成

虽然简单,还是很多人不懂问起这个。简单描述下:

String string="123";
 int x=Integer.parseInt(string);
 System.out.println("1:字符串转数值 "+x);
 
 char c='5';
 int x1=c-'0';
 System.out.println("2:字符转数值 "+x1);
 
 int v=123;
 String s1=String.valueOf(v);
 String s2=Integer.toString(v);
 System.out.println("3:数值转字符串/字符 "+s1+" "+s2);
 
 String str="abc123";
 StringBuffer buf=new StringBuffer();
 char[] ch=str.toCharArray();
 for(int i=0;i<ch.length;i++){
  if(ch[i]>'0' && ch[i]<'9'){
   buf.append(ch[i]);
  }
 }
 int b=Integer.valueOf(buf.toString());
 int b2=Integer.parseInt(buf.toString());
 System.out.println("提取的int值为 "+b+" "+b2);

 int index=buf.indexOf("2");
 System.out.println("字符串\"2\"在串中的位置"+index);
 int index1=str.indexOf("123");
 System.out.println("字符串\"123\"在串中的位置"+index1); 
 
输出:
  1:字符串转数值 123
  2:字符转数值 5
  3:数值转字符串/字符 123 123
  4:提取的int值为 123 123
     字符串"2"在串中的位置1
     字符串"123"在串中的位置3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值