1. String类的重要性
在 C 语言中,字符串通常使用字符数组或字符指针表示,并通过标准库函数操作。然而,这种数据和操作分离的设计不符合面向对象的编程思想。Java 针对字符串的广泛应用,专门提供了功能强大的 String
类,将字符串的数据与操作方法封装在一起,使其更易用、更高效。
2. 常用方法
2.1 字符串构造方式
String
类提供了多种构造方式,以下为常用的几种:
public class Test {
public static void main(String[] args) {
// 双引号引起来的若干字符就是字符串, 即 "hello", 我们称为字符串常量.
String str1 = "hello";
// 把 "hello" 赋值给 引用变量 str1, str1 实际上存的是 "hello" 这个对象 的地址
System.out.println(str1);
// 调用String构造方法传入一个字符串来构造一个字符串对象, 与上文写法相同
String str2 = new String("abc");
System.out.println(str2);
// 把字符数组转变为字符串, 就能得到字符串对象
char[] chars = {'c','x','k'};
String str3 = new String(chars);
System.out.println(str3);
}
}
注意
1. String是引用类型,内部并不存储字符串本身,在String类的实现源码(JDK 9之前)中,String类实例变量如下:
public class Test {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("world");
String s3 = s1;
System.out.println(s3);
System.out.println(s1.length());
}
}
2. JDK 9 之后, String就采用字节数组实现String:
3. 在Java中""
引起来的也是String类型对象。
2.2 String对象的比较
字符串比较在编程中非常常见,例如判断相等、排序等。Java 提供了以下 4 种方式:
1. 使用 ==
比较引用是否相同
==
用于比较两个引用是否指向同一个对象。- 如果两个字符串是不同对象,即使内容相同,
==
也会返回false
。
注意:对于内置类型,==比较的是变量中的值;对于引用类型==比较的是引用中的地址。
2. 使用 equals()
比较内容是否相同
equals()
比较两个字符串的内容是否一致。equalsIgnoreCase()
是equals()
的扩展,忽略大小写进行比较。
public class Test {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equalsIgnoreCase(s2)); // true
int a = 10;
int b = 20;
System.out.println(a == b); // 基本类型 false
}
}
3. 使用 compareTo()
进行字典序比较
compareTo(String s)
比较两个字符串的字典序。- 返回值:
0
:两字符串内容完全相同。- 正数:当前字符串(
this
)大于参数字符串。 - 负数:当前字符串(
this
)小于参数字符串。
- 比较规则:
- 按字典序逐字符比较,若字符不同,返回 ASCII 码差值。
- 如果前 k 个字符相同,返回字符串长度的差值。