[英]Removing white space from an array containing String in Java
So how can I remove a space(s) from an array of a string...那么如何从字符串数组中删除空格...
Taking an example, I have a string called list
:举个例子,我有一个名为list
的字符串:
String[] list ={"Apple ", "Mel on", " Ice -cream ", Television"}; String[] list ={"Apple ", "Mel on", " Ice -cream ", Television"};
Can anyone please guide on what methods I should be using?任何人都可以请指导我应该使用哪些方法? I've already tried using .replace()
.我已经尝试过使用.replace()
。
For a single string:对于单个字符串:
String str = "look! Spaces! ";
System.out.println(str.replaceAll(" ","")); //Will print "look!Spaces!"
For an array:对于数组:
String[] arr = ...
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i].replaceAll(" ", "");
}
Or using Java 8 streams (although this one returns a List
, not an array):或者使用 Java 8 流(尽管这个流返回一个List
,而不是一个数组):
String[] arr = ...
List<String> l = Arrays.stream(arr).map(i -> i.replaceAll(" ", "")).collect(Collectors.toList());
String s1=" hello string ";
System.out.println(s1.trim());
trim()
method only removes leading and trailing white spaces. trim()
方法仅删除前导和尾随空格。 If you want to remove spaces between words like Mel on
, you can use replaceAll() method.如果要删除Mel on
单词之间的空格,可以使用replaceAll()方法。
public static void main(String[] args) {
String[] list ={"Apple ", "Mel on", " Ice -cream ", "Television"};
for (int i = 0; i < list.length; i++) {
list[i] = list[i].replaceAll(" ", "");
}
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
}
Output输出
Apple
Melon
Ice-cream
Television
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.