虽然简单,还是很多人问起这个的。简要描述下:
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