String 是 Java 里最常用的类,表示一串字符。注意它是不可变的。
1. 创建字符串
1 2 3 4 5 6 7 8 9 10 11 12
| public class StringCreateDemo { public static void main(String[] args) { String s1 = "hello";
String s2 = new String("hello");
System.out.println(s1); System.out.println(s2); } }
|
2. 字符串比较:equals 和 ==
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class StringEqualsDemo { public static void main(String[] args) { String s1 = "hello"; String s2 = "hello"; String s3 = new String("hello");
System.out.println(s1.equals(s2)); System.out.println(s1.equals(s3));
System.out.println(s1 == s2); System.out.println(s1 == s3);
System.out.println("Hello".equalsIgnoreCase("hello")); } }
|
结论:比较字符串内容永远用 equals,不要用 ==。
3. 常用方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| public class StringMethodDemo { public static void main(String[] args) { String s = "Hello, Java";
System.out.println(s.length()); System.out.println(s.charAt(0)); System.out.println(s.contains("Java")); System.out.println(s.indexOf("Java")); System.out.println(s.startsWith("Hello")); System.out.println(s.endsWith("Java"));
System.out.println(s.substring(7)); System.out.println(s.substring(0, 5));
String csv = "a,b,c,d"; String[] parts = csv.split(","); System.out.println(parts[0]);
System.out.println(s.replace("Java", "World"));
System.out.println(s.toUpperCase()); System.out.println(s.toLowerCase());
String spaced = " hi "; System.out.println(spaced.trim()); } }
|
4. 字符串不可变
1 2 3 4 5 6 7 8 9
| public class StringImmutableDemo { public static void main(String[] args) { String s = "hello"; s = s + " world";
System.out.println(s); } }
|
因为 String 不可变,频繁拼接会创建很多中间字符串。大量拼接用 StringBuilder。
5. StringBuilder(可变字符串)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class StringBuilderDemo { public static void main(String[] args) { StringBuilder sb = new StringBuilder();
sb.append("Hello"); sb.append(" "); sb.append("Java");
sb.append("!").append(" 欢迎");
System.out.println(sb.toString());
sb.insert(0, ">>"); System.out.println(sb.toString());
System.out.println(sb.reverse()); } }
|
String vs StringBuilder:
| 场景 |
用哪个 |
| 字符串基本不变 |
String |
| 循环里频繁拼接 |
StringBuilder |
1 2 3 4 5 6 7 8 9 10 11
| public class CompareDemo { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100000; i++) { sb.append(i); } String result = sb.toString(); System.out.println(result.length()); } }
|
小结
- 比较内容用
equals,不用 ==
String 不可变,频繁拼接用 StringBuilder
- 常用:
length charAt equals contains indexOf substring split replace trim