Java中String的几个常用构造方法
关于String类常用的构造方法:
1、String s = “”; (这是用的最多的)
2、String s = new String(“”);
3、String s = new String(byte[] bytes);
4、String s = new String(byte[] bytes, int offset, int length);
5、String s = new String(char[] chars);
6、String s = new String(char[] chars, int offset, int length);
测试代码:
public class Test03 {
public static void main(String[] args) {
//用的最多的字符串初始化是
String s1 = "hello world";
System.out.println(s1); //输出:hello world
//new String(String str)
String s2 = new String("good job");
System.out.println(s2); //输出:good job
//new String(byte[] bytes)
byte[] bytes = { 97, 98, 99, 100}; //48-57:0-9 65-90:A-Z 97-122:a-z
String s3 = new String(bytes);
System.out.println(s3); //输出:abcd
//new String(byte[] bytes, int offset, int length) 其中offset是数组的起始下标,length是长度
String s4 = new String(bytes, 1, 3);
System.out.println(s4); //输出:bcd
//new String(char[] chars)
char[] chars = { 's', 't', 'u', 'd', 'e', 'n', 't'};
String s5 = new String(chars);
System.out.println(s5); //输出:student
//new String(char[] chars, int offset, int length)
char[] chars1 = { '我', '是', '中', '国', '人'};
String s6 = new String(chars1, 2, 3);
System.out.println(s6); //输出:中国人
}
}
还没有评论,来说两句吧...