How to trim white space from all elements in array

2020-02-23 06:01发布

I was just wondering what the best way to remove the white space from all the elements of a list would be.

For example if I had String [] array = {" String", "Tom Selleck "," Fish "} How could I get all the elements as {"String","Tom Selleck","Fish"}

Thanks!

8条回答
可以哭但决不认输i
2楼-- · 2020-02-23 06:38

In Java 8, Arrays.parallelSetAll seems ready made for this purpose:

import java.util.Arrays;

Arrays.parallelSetAll(array, (i) -> array[i].trim());

This will modify the original array in place, replacing each element with the result of the lambda expression.

查看更多
▲ chillily
3楼-- · 2020-02-23 06:41

Add commons-lang3-3.1.jar in your application build path. Use the below code snippet to trim the String array.

String array = {" String", "Tom Selleck "," Fish "};
array = StringUtils.stripAll(array);
查看更多
乱世女痞
4楼-- · 2020-02-23 06:42
String val = "hi hello prince";
String arr[] = val.split(" ");

for (int i = 0; i < arr.length; i++)
{   
     System.out.print(arr[i]);
}
查看更多
我命由我不由天
5楼-- · 2020-02-23 06:48

You can just iterate over the elements in the array and call array[i].trim() on each element

查看更多
Fickle 薄情
6楼-- · 2020-02-23 06:49

Try this:

String[] trimmedArray = new String[array.length];
for (int i = 0; i < array.length; i++)
    trimmedArray[i] = array[i].trim();

Now trimmedArray contains the same strings as array, but without leading and trailing whitespace. Alternatively, you could write this for modifying the strings in-place in the same array:

for (int i = 0; i < array.length; i++)
    array[i] = array[i].trim();
查看更多
劳资没心,怎么记你
7楼-- · 2020-02-23 06:49

I know this is a really old post, but since Java 1.8 there is a nicer way to trim every String in an array.

Java 8 Lamda Expression solution:

List<String> temp = new ArrayList<>(Arrays.asList(yourArray));
temp.forEach(e -> {temp.set((temp.indexOf(e), e.trim()});
yourArray = temp.toArray(new String[temp.size()]);

with this solution you don't have to create a new Array.
Like in Óscar López's solution

查看更多
登录 后发表回答