String
String 是 Java 中使用频率最高的类,表示不可变的字符串——任何"修改"操作实际上都会创建新对象。
创建方式
String s1 = "hello"; // 字面量,存入字符串常量池
String s2 = "hello"; // 与 s1 指向同一对象
String s3 = new String("hello"); // new 出独立对象
System.out.println(s1 == s2); // true(常量池复用)
System.out.println(s1 == s3); // false(地址不同)
System.out.println(s1.equals(s3)); // true(内容相同)
常用方法
| 方法 | 说明 | 示例 |
|---|---|---|
length() | 长度 | "abc".length() → 3 |
charAt(i) | 取字符 | "abc".charAt(1) → 'b' |
substring(a, b) | 截取 [a, b) | "hello".substring(1, 3) → "el" |
indexOf(s) | 查找位置 | "hello".indexOf("ll") → 2 |
contains(s) | 是否包含 | "hello".contains("ell") → true |
startsWith / endsWith | 前缀/后缀判断 | "a.java".endsWith(".java") → true |
replace(a, b) | 替换 | "aab".replace('a', 'c') → "ccb" |
trim() | 去首尾空白 | " hi ".trim() → "hi" |
toUpperCase / toLowerCase | 大小写 | "ab".toUpperCase() → "AB" |
split(regex) | 拆分 | "a,b,c".split(",") → 数组 |
equals / equalsIgnoreCase | 内容比较 | 见下方注意 |
拆分与拼接
String csv = "apple,banana,orange";
String[] fruits = csv.split(","); // ["apple", "banana", "orange"]
String joined = String.join(" | ", fruits); // "apple | banana | orange"
格式化
String msg = String.format("姓名:%s,年龄:%d,成绩:%.1f", "Alice", 18, 95.5);
判空注意
String s = null;
// s.length(); // 会抛 NullPointerException
if (s != null && !s.isEmpty()) { ... } // 安全写法
比较字符串内容一律使用 equals(),并且把已知字面量放前面更防空指针:"admin".equals(input)。