在 Java 中,String
类是最常用的数据类型之一,它代表不可变的字符串。String
提供了丰富的 API,用于字符串操作,如查找、替换、截取、格式化等。
✅ 1. 创建字符串 Java 提供了多种方式来创建字符串:
1 2 3 4 String s1 = "Hello" ; String s2 = new String ("Hello" ); char [] chars = {'H' , 'e' , 'l' , 'l' , 'o' };String s3 = new String (chars);
✅ 2. 字符串基本操作 (1)获取字符串长度 1 2 3 String str = "Hello, World!" ;int length = str.length(); System.out.println(length);
(2)获取字符串中的某个字符 1 2 char ch = str.charAt(0 ); System.out.println(ch);
(3)字符串拼接 1 2 3 4 String s1 = "Hello" ;String s2 = " World" ;String result = s1.concat(s2); System.out.println(result);
⚠ 注意 :尽量使用 StringBuilder
进行拼接,String
的拼接会创建新的对象,效率较低。
✅ 3. 查找与匹配 (1)判断是否包含子字符串 1 2 boolean contains = str.contains("World" ); System.out.println(contains);
(2)判断是否以某个前缀或后缀开头 1 2 System.out.println(str.startsWith("Hello" )); System.out.println(str.endsWith("!" ));
(3)获取子字符串的位置 1 2 int index = str.indexOf("World" ); int lastIndex = str.lastIndexOf("o" );
✅ 4. 字符串截取 1 2 3 4 5 String sub = str.substring(7 ); System.out.println(sub); String sub2 = str.substring(7 , 12 ); System.out.println(sub2);
✅ 5. 替换字符串 (1)替换单个字符 1 2 String newStr = str.replace('o' , '0' ); System.out.println(newStr);
(2)替换子字符串 1 2 String newStr2 = str.replace("World" , "Java" ); System.out.println(newStr2);
(3)使用正则表达式替换 1 2 String replaced = str.replaceAll("\\w+" , "X" ); System.out.println(replaced);
✅ 6. 分割字符串 1 2 3 4 5 String data = "apple,banana,orange" ; String[] fruits = data.split("," );for (String fruit : fruits) { System.out.println(fruit); }
输出:
✅ 7. 大小写转换 1 2 System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase());
✅ 8. 去除首尾空格 1 2 String spaced = " Hello World! " ; System.out.println(spaced.trim());
✅ 9. 字符串比较 (1)区分大小写 1 2 3 String a = "hello" ;String b = "Hello" ; System.out.println(a.equals(b));
(2)忽略大小写比较 1 System.out.println(a.equalsIgnoreCase(b));
(3)按字典顺序比较 1 2 3 System.out.println("abc" .compareTo("abd" )); System.out.println("abc" .compareTo("abc" )); System.out.println("abd" .compareTo("abc" ));
✅ 10. 格式化字符串 1 2 3 String formatted = String.format("My name is %s and I am %d years old." , "Alice" , 25 ); System.out.println(formatted);
✅ 11. 判断字符串是否为空 1 2 3 String emptyStr = "" ; System.out.println(emptyStr.isEmpty()); System.out.println(emptyStr.isBlank());
✅ 12. 使用 StringBuilder
进行高效拼接 1 2 3 StringBuilder sb = new StringBuilder (); sb.append("Hello" ).append(" " ).append("World!" ); System.out.println(sb.toString());
✅ 总结
方法
作用
length()
获取字符串长度
charAt(index)
获取指定索引位置的字符
concat(str)
拼接字符串
contains(str)
判断是否包含子字符串
startsWith(str) / endsWith(str)
判断是否以某字符串开头/结尾
indexOf(str) / lastIndexOf(str)
获取子字符串的索引位置
substring(start, end)
截取子字符串
replace(old, new)
替换字符串
replaceAll(regex, new)
使用正则表达式替换字符串
split(regex)
按照正则表达式分割字符串
toUpperCase() / toLowerCase()
转换大小写
trim()
去除首尾空格
equals(str) / equalsIgnoreCase(str)
字符串比较
compareTo(str)
按字典顺序比较
isEmpty() / isBlank()
判断字符串是否为空
String.format()
字符串格式化
StringBuilder
高效字符串拼接