方法 1:使用 String.replace() 或 String.replaceAll()
适用于删除所有匹配的字符或符合特定模式的字符。

示例 1:删除所有特定字符
String str = "Hello, World!"; char toRemove = 'l'; String result = str.replace(String.valueOf(toRemove), ""); // 删除所有 'l' System.out.println(result); // 输出: Heo, Word!
示例 2:使用正则表达式删除所有数字
String str = "abc123def456";
String result = str.replaceAll("\\d", ""); // 删除所有数字
System.out.println(result); // 输出: abcdef
方法 2:使用 StringBuilder 或 StringBuffer
适用于需要删除特定位置的字符(删除第 n 个字符)。
示例:删除指定索引的字符
String str = "Hello, World!"; int indexToRemove = 7; // 删除 'W' StringBuilder sb = new StringBuilder(str); sb.deleteCharAt(indexToRemove); String result = sb.toString(); System.out.println(result); // 输出: Hello, orld!
方法 3:使用 String.substring()
适用于删除从某个位置开始到字符串末尾或某个范围内的字符。
示例 1:删除从某个位置开始的所有字符
String str = "Hello, World!"; int startIndex = 5; // 删除从索引 5 开始的所有字符 String result = str.substring(0, startIndex); System.out.println(result); // 输出: Hello
示例 2:删除某个范围内的字符
String str = "Hello, World!"; int start = 7; int end = 12; String result = str.substring(0, start) + str.substring(end); System.out.println(result); // 输出: Hello, d!
方法 4:使用 String.replaceAll() 结合正则表达式
适用于删除符合特定模式的子串(删除所有非字母字符)。
示例:删除所有非字母字符
String str = "H3llo, W0rld!";
String result = str.replaceAll("[^a-zA-Z]", ""); // 只保留字母
System.out.println(result); // 输出: HlloWrld
方法 5:使用 String.chars() + filter(Java 8+)
适用于基于条件删除字符(删除所有小写字母)。

示例:删除所有小写字母
String str = "Hello, World!";
String result = str.chars()
.filter(c -> !Character.isLowerCase(c))
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
System.out.println(result); // 输出: H, W!
方法 6:使用 StringUtils(Apache Commons Lang)
如果你使用 Apache Commons Lang 库,可以使用 StringUtils.remove() 或 StringUtils.replaceChars()。
示例 1:删除所有特定字符
import org.apache.commons.lang3.StringUtils; String str = "Hello, World!"; String result = StringUtils.remove(str, 'l'); // 删除所有 'l' System.out.println(result); // 输出: Heo, Word!
示例 2:替换多个字符
String str = "Hello, World!"; String result = StringUtils.replaceChars(str, "lW", ""); // 删除 'l' 和 'W' System.out.println(result); // 输出: Heo, ord!
| 方法 | 适用场景 | 示例 |
|---|---|---|
String.replace() / replaceAll() |
删除所有匹配的字符或正则表达式 | str.replace("l", "") |
StringBuilder.deleteCharAt() |
删除特定索引的字符 | sb.deleteCharAt(7) |
String.substring() |
删除某个范围内的字符 | str.substring(0, 5) |
String.replaceAll() + 正则 |
删除符合特定模式的字符 | str.replaceAll("[^a-zA-Z]", "") |
String.chars() + filter |
基于条件删除字符(Java 8+) | filter(c -> !Character.isLowerCase(c)) |
StringUtils.remove() |
使用 Apache Commons Lang | StringUtils.remove(str, 'l') |
选择最适合你需求的方法即可!
