说到字符串,只要有一点点常识的人都知道字符串是什么,我一般会直接使用 String 类定义
注意:字符串变量必须经过初始化才能使用
如何将字串 String 转换成整数 int
String 字符串转整型 int 有以下两种方式:
Integer.parseInt(str)
Integer.valueOf(str).intValue()
代码:
public class DemoString {
public static void main(String[] args) {
String str = “123”;
int n = 0;
// 第一种转换方法:Integer.parseInt(str)
n = Integer.parseInt(str);
System.out.println("第一种方法 : " + n);
// 第二种转换方法:Integer.valueOf(str).intValue()
n = 0;
n = Integer.valueOf(str).intValue();
System.out.println("第二种方法 : " + n);
//修改了 a 数组中第 2 个元素的值
char a[]={‘H’,‘e’,‘l’,‘l’,‘o’};
String sChar=new String(a,1,4);
a[1]=‘s’;
System.out.println(“修改后的a:”+sChar);
}
}
结果如下图:

这两种方法有什么区别呢?作用是不是一样的呢?是不是在任何下都能互换呢?
第一种方法:i=Integer.parseInt(str); //直接使用静态方法,不会产生多余的对象,但会抛出异常
第二种方法:i=Integer.valueOf(str).intValue(); //Integer.valueOf(s) 相当于 new Integer(Integer.parseInt(s)),也会抛异常,但会多产生一个对象
如何将整数 int 转换成字串 String ?
整型 int 转 String 字符串类型有以下 3 种方法:
String s = String.valueOf(i);
String s = Integer.toString(i);
String s = “” + i;
代码:
public class DemoString {
public static void main(String[] args) {
int num = 10;
// 第一种方法:String.valueOf(i);
num = 10;
String s = String.valueOf(num);
System.out.println(“s:” + s);
// 第二种方法:Integer.toString(i);
num = 10;
String s2 = Integer.toString(num);
System.out.println(“s2:” + s2);
// 第三种方法:"" + i;
String s3 = num + “”;
System.out.println(“s3:” + s3);
}
}
答案:

第一种方法:s=i+"";
第二种方法:s=String.valueOf(i);
这两种方法有什么区别呢?作用是不是一样的呢?是不是在任何下都能互换呢?
第一种方法:s=i+""; //会产生两个String对象
第二种方法:s=String.valueOf(i); //直接使用String类的静态方法,只产生一个对象
注意:字符串变量必须经过初始化才能使用
如何将字串 String 转换成整数 int
String 字符串转整型 int 有以下两种方式:
Integer.parseInt(str)
Integer.valueOf(str).intValue()
代码:
public class DemoString {
public static void main(String[] args) {
String str = “123”;
int n = 0;
// 第一种转换方法:Integer.parseInt(str)
n = Integer.parseInt(str);
System.out.println("第一种方法 : " + n);
// 第二种转换方法:Integer.valueOf(str).intValue()
n = 0;
n = Integer.valueOf(str).intValue();
System.out.println("第二种方法 : " + n);
//修改了 a 数组中第 2 个元素的值
char a[]={‘H’,‘e’,‘l’,‘l’,‘o’};
String sChar=new String(a,1,4);
a[1]=‘s’;
System.out.println(“修改后的a:”+sChar);
}
}
结果如下图:

这两种方法有什么区别呢?作用是不是一样的呢?是不是在任何下都能互换呢?
第一种方法:i=Integer.parseInt(str); //直接使用静态方法,不会产生多余的对象,但会抛出异常
第二种方法:i=Integer.valueOf(str).intValue(); //Integer.valueOf(s) 相当于 new Integer(Integer.parseInt(s)),也会抛异常,但会多产生一个对象
如何将整数 int 转换成字串 String ?
整型 int 转 String 字符串类型有以下 3 种方法:
String s = String.valueOf(i);
String s = Integer.toString(i);
String s = “” + i;
代码:
public class DemoString {
public static void main(String[] args) {
int num = 10;
// 第一种方法:String.valueOf(i);
num = 10;
String s = String.valueOf(num);
System.out.println(“s:” + s);
// 第二种方法:Integer.toString(i);
num = 10;
String s2 = Integer.toString(num);
System.out.println(“s2:” + s2);
// 第三种方法:"" + i;
String s3 = num + “”;
System.out.println(“s3:” + s3);
}
}
答案:

第一种方法:s=i+"";
第二种方法:s=String.valueOf(i);
这两种方法有什么区别呢?作用是不是一样的呢?是不是在任何下都能互换呢?
第一种方法:s=i+""; //会产生两个String对象
第二种方法:s=String.valueOf(i); //直接使用String类的静态方法,只产生一个对象