目录
String
字符串构造
String的构造最常用的就是一下三种:
String s1 = "hello";//直接赋值
System.out.println(s1);
//通过new来赋值
String s2 = new String("hahahhaha");
System.out.println(s2);
//用char类型数组存储,来new数组
char[] array = {'a','b','c'};
String s3 = new String(array);
System.out.println(s3);
String是一个引用类型,内部并不存放字符串本身
public static void main(String[] args) {
//s1和s2引用的是不同的对象,s1和s3引用的是相同的对象
String s1 = "hello";
String s2 = "world";
String s3 = s1;
//这是一个字符判空函数,如果s1里面存放值为false
//没有存放值为true
System.out.println(s1.isEmpty());
}
String对象的比较
字符串的比较是java中很常见的,下面为大家介绍4种比较方法:
1.
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abcd";
String s3 = "abc";
System.out.println(s1 == s2);//结果为false
System.out.println(s1 == s3);//结果为true
}
通过 == 比较,比较的是引用数据类型的地址,地址相同则为true,不同则为false
2.
ublic static void main(String[] args) {
String s1 = "abc";
String s2 = "abcd";
String s3 = "abc";
System.out.println(s1.equals(s2));//结果为false
System.out.println(s1.equals(s3));//结果为true
}
通过 equals 方法比较,比较的是字符串里面存放的内容是否相同,
相同为true,不同为false
3.
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abcd";
String s3 = "abc";
String s4 = "abcdEFG";
System.out.println(s1.compareTo(s2));//结果为-1
System.out.println(s1.compareTo(s3));//结果为0
System.out.println(s1.compareTo(s4));//结果为-3
}
通过 comparableTo 方法比较,比较的是字符串内容不相同的个数,
相同为0,不相同为 负的个数(有x个不相同,结果就为-x)
4.
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abcd";
String s3 = "ABC";
String s4 = "abcdEFG";
String s5 = "ABCdefg";
System.out.println(s1.compareToIgnoreCase(s2));//结果为-1
System.out.println(s1.compareToIgnoreCase(s3));//结果为0
System.out.println(s1.compareToIgnoreCase(s4));//结果为-4
System.out.println(s4.compareToIgnoreCase(s5));//结果为0
}
通过 compareToIgnoreCase 方法比较,与compareTo 方法相同,唯一的区别就是不区分大小写
字符串的查找
举例: