将字符串12345转换成整数12345
public class StringCharTest {
public static void main(String[] args) {
String str1 = new String("hello");
System.out.println("str1 = " + str1);
System.out.println("字符串的长度是:" + str1.length());
System.out.println("下标为0的字符是:" + str1.charAt(0));
System.out.println("下标为1的字符是:" + str1.charAt(1));
System.out.println("下标为2的字符是:" + str1.charAt(2));
System.out.println("下标为3的字符是:" + str1.charAt(3));
System.out.println("下标为4的字符是:" + str1.charAt(4));
System.out.println("--------------------------------------");
for(int i = 0; i < str1.length(); i++) {
System.out.println("下标为" + i + "的元素是:" + str1.charAt(i));
}
System.out.println("--------------------------------------");
练习:使用两种方式实现将字符串"12345"转换为整数12345并打印出来
String str2 = new String("12345");
int ia = Integer.parseInt(str2);
System.out.println("ia = " + ia);
int ib = 0;
for(int i = 0; i < str2.length(); i++) {
ib = ib*10 + (str2.charAt(i)-'0');
}
System.out.println("ib = " + ib);
System.out.println("--------------------------------------");
扩展:使用两种方式实现int类型转换为String并打印
String str3 = String.valueOf(ib);
System.out.println("str3 = " + str3);
String str4 = "" + ib;
System.out.println("str4 = " + str4);
}
}