Java学习笔记92——String类概述及其构造方法
字符串:
简单理解: 就是由多个字符组成的数据,叫做字符串 也可以看作是一个字符数组。
观察API发现:
1、String代表的是字符串,属于java.lang下面的,所以使用的时候不需要导包 2、String类代表字符串。 Java程序中的所有字符串文字(例如"abc" )都被实现为此类的实例。(对象) 3、字符串不变; 它们的值在创建后不能被更改 字符串是常量,一旦被赋值,就不能改变
构造方法:
public String() public String(byte[] bytes) public String(byte[] bytes,int offset,int length) public String(char[] value) public String(char[] value,int offset,int count) public String(String original)
注意事项:
1、String类重写了toString()方法
public class StringDemo {
public static void main(String[] args) {
//public String()
String s = new String();
System.out.println("s: " + s);
//查看字符串的长度
//public int length()返回此字符串的长度。
System.out.println("字符串s的长度为:" + s.length());
System.out.println("***************************************");
//public String(byte[] bytes) 将一个字节数组转成一个字符串
byte[] b = {97,98,99,100,101};
String s2 = new String(b);
System.out.println("s2: " + s2);//abcde(将每个字符自动转化成对应的ASCII码值显示出来)
//查看字符串的长度
//public int length()返回此字符串的长度。
System.out.println("字符串s的长度为:" + s2.length());
System.out.println("***************************************");
//public String(byte[] bytes,int index,int length)
//将字节数组中的一部分截取出来变成一个字符串
String s3 = new String(b, 1, 3);//从下标(索引)位置为3开始从左向右数三个
System.out.println("s3: " + s3);
//查看字符串的长度
//public int length()返回此字符串的长度。
System.out.println("字符串s的长度为:" + s3.length());
System.out.println("***************************************");
//StringIndexOutOfBoundsException(下标位置和截取长度必须都要合理,否则报错)
// String s4 = new String(b, 1, 5);
// System.out.println("s4: " + s4);
// //查看字符串的长度
// //public int length()返回此字符串的长度。
// System.out.println("字符串s的长度为:" + s4.length());
System.out.println("***************************************");
//public String(char[] value) 将一个字符数组转成一个字符串
char[] c = {'a','b','c','d','我','爱','冯','提','莫'};
String s5 = new String(c);
System.out.println("s5: " + s5);
//查看字符串的长度
//public int length()返回此字符串的长度。
System.out.println("字符串s的长度为:" + s5.length());
System.out.println("***************************************");
//public String(char[] value,int offset,int count)
//将字符数组中一部分截取出来变成一个字符串
String s6 = new String(c, 4, 5);
System.out.println("s6: " + s6);
//查看字符串的长度
//public int length()返回此字符串的长度。
System.out.println("字符串s的长度为:" + s6.length());
System.out.println("***************************************");
//public String(String original)
String s7 = "你好";
String s8 = new String(s7);
System.out.println("s8: " + s8);
//查看字符串的长度
//public int length()返回此字符串的长度。
System.out.println("字符串s的长度为:" + s8.length());
}
}


浙公网安备 33010602011771号