所属包:java.lang.String
Java程序中所有的字符串字面值(如:“abc”)都作为此类的势力实现。其实就是说程序中所有的双引号的字符串都是String类的对象。(就算没有new,也都是)
字符串的特点:
1.字符串的内容永不可变【切记】
2.由于字符串不可改变,则所有的字符串都可共享使用。
String a= "abc";
String b = "abc";
System.out.println(a==b);//结果为true
其实在这里,a 和 b 比较的是他们在内存中的地址值。这里需要引入一个概念:程序中直接用双引号""包起来的字符串,就在字符串的常量池中。也就是说,只有用双引号括起来的字符串,才在字符串常量池中。那么我们的a和b 接收的都是"abc" 在字符串常量池中的地址值。
3.字符串效果上相当于一个char[] 字符数组,但是底层是byte[]字节数组
直接使用 == 比较字符串是比较的他们的内存值,那么我们要怎样比较两个字符串的内容是不是一样的呢?
public boolean equals(Object obj) {}(区分大小写)
public static void main(String[] args) {
String a= "abc";
String b = "abc";
String c = "equals";
char[] charArray = {'a','b','c'};
String str = new String(charArray);
System.out.println(a.equals(b));// true
System.out.println(a.equals(str));// true
System.out.println(a.equals(c));// false
System.out.println("abcd".equals(b));// false
}
public boolean equalsIgnoreCase(){} (不区分大小写)
public static void main(String[] args) {
String a= "abc";
String b = "Abc";
char[] charArray = {'A','B','C'};
String str = new String(charArray);
System.out.println(a.equalsIgnoreCase(b));//true
System.out.println(a.equalsIgnoreCase(str));//true
}
public int length(){} 获取字符串的字符个数,拿到字符串长度
public static void main(String[] args) {
String a= "abcdfjkhiegkdj";
System.out.println(a.length());// 14
}
public String concat(String str){} 拼接字符串,将当前字符串和参数字符串进行拼接
public static void main(String[] args) {
String a= "Hello";
String b = "World";
System.out.println(a.concat(b));// HelloWorld
}
public char charAt(int index){} 获取指定索引位置的字符。(索引是从0开始)
public static void main(String[] args) { String a= "Hello,World!"; System.out.println(a.charAt(3));// 'l' }
public int indexOf(String str){}
查找参数 字符串 在本字符串中第一次出现的位置索引。没有就返回-1.
public static void main(String[] args) { String a= "Hello,World!"; System.out.println(a.indexOf("llo"));// 2 }
字符串的截取:
public String substring(int index){} 从参数索引处开始截取后面的所有字符,返回新的字符串
public String substring(int begin,int end){} 截取从 begin 开始 到end 结束,中间的字符串。
注意:[begin,end)是左闭右开区间
public static void main(String[] args) {
String a= "Hello,World!";
String b = a.substring(4);
String c = a.substring(2,6);
System.out.println(b);//o,World!
System.out.println(c);//llo,
}