java如何去除语句
去除字符串中的空格
使用 trim() 方法可以去除字符串首尾的空格。该方法返回一个新的字符串,原字符串不受影响。
String str = " Hello World ";
String trimmedStr = str.trim();
System.out.println(trimmedStr); // 输出 "Hello World"
去除字符串中的所有空格
使用 replaceAll() 方法配合正则表达式可以去除字符串中的所有空格。

String str = " Hello World ";
String noSpaceStr = str.replaceAll("\\s", "");
System.out.println(noSpaceStr); // 输出 "HelloWorld"
去除特定字符
使用 replace() 方法可以去除字符串中的特定字符。该方法支持字符或字符串替换。
String str = "Hello-World";
String newStr = str.replace("-", "");
System.out.println(newStr); // 输出 "HelloWorld"
使用正则表达式去除复杂模式
对于更复杂的模式,可以使用 replaceAll() 方法配合正则表达式。例如,去除所有非字母字符。

String str = "Hello123World!";
String lettersOnly = str.replaceAll("[^a-zA-Z]", "");
System.out.println(lettersOnly); // 输出 "HelloWorld"
使用 Apache Commons Lang 库
Apache Commons Lang 库提供了 StringUtils 类,其中包含更多字符串操作工具。
import org.apache.commons.lang3.StringUtils;
String str = " Hello World ";
String trimmedStr = StringUtils.trim(str);
String noSpaceStr = StringUtils.deleteWhitespace(str);
使用 Java 8 的 Stream API
对于更复杂的处理,可以使用 Java 8 的 Stream API 来过滤字符。
String str = "Hello123World!";
String filteredStr = str.chars()
.filter(c -> Character.isLetter(c))
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
System.out.println(filteredStr); // 输出 "HelloWorld"






