java 如何去掉
去掉字符串中的空格
在Java中,可以使用String类的replace()方法或replaceAll()方法来去掉字符串中的空格。replace()方法用于替换字符或字符串,而replaceAll()方法支持正则表达式。
String str = " Hello World ";
String result = str.replace(" ", ""); // 去掉所有空格
System.out.println(result); // 输出 "HelloWorld"
使用replaceAll()方法可以通过正则表达式匹配所有空白字符(包括空格、制表符、换行符等):
String str = " Hello \t World \n ";
String result = str.replaceAll("\\s", ""); // 去掉所有空白字符
System.out.println(result); // 输出 "HelloWorld"
去掉字符串首尾的空格
如果只需要去掉字符串首尾的空格,可以使用String类的trim()方法。该方法会去掉字符串开头和结尾的所有空白字符。

String str = " Hello World ";
String result = str.trim(); // 去掉首尾空格
System.out.println(result); // 输出 "Hello World"
在Java 11及以上版本,还可以使用strip()方法,它比trim()更智能,能处理Unicode空白字符:
String str = " Hello World ";
String result = str.strip(); // 去掉首尾空格(包括Unicode空白字符)
System.out.println(result); // 输出 "Hello World"
去掉集合中的空元素
如果需要从集合(如List)中移除空元素(如null或空字符串),可以使用removeIf()方法或流式操作。

List<String> list = new ArrayList<>();
list.add("Hello");
list.add("");
list.add(null);
list.add("World");
// 使用removeIf移除null或空字符串
list.removeIf(s -> s == null || s.isEmpty());
System.out.println(list); // 输出 ["Hello", "World"]
使用Java 8的流式操作过滤空元素:
List<String> filteredList = list.stream()
.filter(s -> s != null && !s.isEmpty())
.collect(Collectors.toList());
System.out.println(filteredList); // 输出 ["Hello", "World"]
去掉数组中的空元素
如果需要从数组中移除空元素(如null或空字符串),可以先将数组转换为列表,再过滤空元素,最后转换回数组。
String[] array = {"Hello", "", null, "World"};
List<String> list = new ArrayList<>(Arrays.asList(array));
list.removeIf(s -> s == null || s.isEmpty());
array = list.toArray(new String[0]);
System.out.println(Arrays.toString(array)); // 输出 ["Hello", "World"]
使用Java 8的流式操作过滤空元素:
String[] filteredArray = Arrays.stream(array)
.filter(s -> s != null && !s.isEmpty())
.toArray(String[]::new);
System.out.println(Arrays.toString(filteredArray)); // 输出 ["Hello", "World"]






