一、创建和基本信息
1. 创建字符串
String str1 = "Hello";
String str2 = new String("Hello");
char[] chars = {'H','e','l','l','o'};
String str3 = new String(chars);
byte[] bytes = {72, 101, 108, 108, 111};
String str4 = new String(bytes);
2. 基本信息和比较
String s = "Hello World";
int len = s.length();
boolean empty = s.isEmpty();
char c = s.charAt(0);
boolean eq1 = s.equals("hello world");
boolean eq2 = s.equalsIgnoreCase("hello world");
int cmp = s.compareTo("Hello");
二、查找和判断
1. 查找字符/子串
String s = "Hello World";
int index1 = s.indexOf('o');
int index2 = s.lastIndexOf('o');
int index3 = s.indexOf("World");
int index4 = s.indexOf('o', 5);
boolean contains = s.contains("World");
2. 判断开头/结尾
String s = "HelloWorld.java";
boolean starts = s.startsWith("Hello");
boolean ends = s.endsWith(".java");
boolean starts2 = s.startsWith("World", 5);
3. 匹配判断
String s = "Hello123";
boolean matches = s.matches("^Hello\\d+$");
三、截取和分割
1. 截取子串
String s = "Hello World";
String sub1 = s.substring(6);
String sub2 = s.substring(0, 5);
2. 分割字符串
String csv = "apple,orange,banana";
String[] fruits = csv.split(",");
String complex = "a,b;c:d";
String[] arr = complex.split("[,;:]");
String limited = "1-2-3-4-5";
String[] parts = limited.split("-", 3);
四、转换和修改
1. 大小写转换
String s = "Hello World";
String upper = s.toUpperCase();
String lower = s.toLowerCase();
2. 去除空白
String s = " Hello World ";
String trimmed = s.trim();
String stripped = s.strip();
String leading = s.stripLeading();
String trailing = s.stripTrailing();
3. 替换内容
String s = "Hello World";
String rep1 = s.replace('l', 'L');
String rep2 = s.replace("World", "Java");
String rep3 = s.replaceAll("\\s+", "-");
String rep4 = s.replaceFirst("l", "L");
4. 格式化
String format = String.format("姓名:%s,年龄:%d,成绩:%.2f",
"张三", 20, 95.5);
String joined = String.join("-", "2023", "12", "31");
五、字符数组和字节数组
1. 与字符数组互转
String s = "Hello";
char[] chars = s.toCharArray();
String fromChars = new String(chars);
String joinChars = String.valueOf(chars);
2. 与字节数组互转
String s = "Hello";
byte[] bytes1 = s.getBytes();
byte[] bytes2 = s.getBytes("UTF-8");
byte[] bytes3 = s.getBytes(StandardCharsets.UTF_8);
String fromBytes = new String(bytes1);
String fromBytes2 = new String(bytes2, "UTF-8");
六、其他实用方法
1. 重复和缩进
String repeated = "Java".repeat(3);
String indented = "Hello\nWorld".indent(2);
2. 转换方法
String s1 = String.valueOf(123);
String s2 = String.valueOf(3.14);
String s3 = String.valueOf(true);
String s4 = String.valueOf(new Object());
String s5 = Integer.toString(100);
String s6 = Double.toString(3.1415);
3. 判断空白
String s1 = " ";
String s2 = "";
boolean blank1 = s1.isBlank();
boolean blank2 = s2.isBlank();
boolean empty = s2.isEmpty();
七、StringBuilder 和 StringBuffer
1. StringBuilder(非线程安全,性能好)
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
sb.insert(5, ",");
sb.delete(5, 6);
sb.reverse();
String result = sb.toString();
2. StringBuffer(线程安全)
StringBuffer sb = new StringBuffer();
八、性能提示和最佳实践
1. 字符串比较
if (str == "test") { ... }
if ("test".equals(str)) { ... }
if (str != null && str.equals("test")) { ... }
2. 字符串拼接
String result = "";
for (int i = 0; i < 100; i++) {
result += i;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) {
sb.append(i);
}
String result = sb.toString();
3. 字符串池
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));
九、实际应用示例
public class StringExample {
public static void main(String[] args) {
String path = "/usr/local/bin/java";
String filename = path.substring(path.lastIndexOf("/") + 1);
String extension = filename.substring(filename.lastIndexOf(".") + 1);
String email = "user@example.com";
boolean isValid = email.matches("^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$");
String csv = "John,Doe,30,New York";
String[] fields = csv.split(",");
String template = "用户:%s,积分:%d,等级:%c";
String message = String.format(template, "Alice", 1500, 'A');
String phone = "13800138000";
String masked = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
}
}
总结要点
- 不可变性:String对象一旦创建不可修改,所有"修改"操作都返回新对象
- 字符串池:字面量创建的字符串会放入常量池,可复用
- 性能考虑:频繁修改用StringBuilder/StringBuffer
- 编码注意:处理中文等非ASCII字符时注意编码问题
- null安全:使用
"text".equals(str)避免NPE