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 removedStr = str.replace("-", "").replace("!", "");
System.out.println(removedStr); // 输出 "HelloWorld"
使用正则表达式去除复杂模式
通过正则表达式可以匹配更复杂的模式并去除。例如,去除所有非字母数字字符:
String str = "Hello@World#123";
String cleanedStr = str.replaceAll("[^a-zA-Z0-9]", "");
System.out.println(cleanedStr); // 输出 "HelloWorld123"
使用 Apache Commons Lang 库
Apache Commons Lang 库提供了 StringUtils 类,包含更多字符串操作工具方法。例如去除所有空格:

import org.apache.commons.lang3.StringUtils;
String str = " Hello World ";
String cleanedStr = StringUtils.deleteWhitespace(str);
System.out.println(cleanedStr); // 输出 "HelloWorld"






