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条回答
走好不送
2楼-- · 2020-02-23 06:50

Another java 8 lambda option :

String[] array2 = Arrays.stream(array).map(String::trim).toArray(String[]::new);

And the ugly but optimized version without new array creation

Arrays.stream(array).map(String::trim).toArray(unused -> array);

Original "array" is modified.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-02-23 06:52

Not knowing how the OP happened to have {" String", "Tom Selleck "," Fish "} in an array in the first place (6 years ago), I thought I'd share what I ended up with.

My array is the result of using split on a string which might have extra spaces around delimiters. My solution was to address this at the point of the split. My code follows. After testing, I put splitWithTrim() in my Utils class of my project. It handles my use case; you might want to consider what sorts of strings and delimiters you might encounter if you decide to use it.

public class Test {
    public static void main(String[] args) {
        test(" abc def  ghi   jkl ", " ");
        test("  abc; def  ;ghi  ; jkl; ", ";");
    }

    public static void test(String str, String splitOn) {
        System.out.println("Splitting \"" + str + "\" on \"" + splitOn + "\"");
        String[] parts = splitWithTrim(str, splitOn);
        for (String part : parts) {
            System.out.println("(" + part + ")");
        }
    }

    public static String[] splitWithTrim(String str, String splitOn) {
        if (splitOn.equals(" ")) {
            return str.trim().split(" +");
        } else {
            return str.trim().split(" *" + splitOn + " *");
        }
    }
}

Output of running the test application is:

Splitting " abc def  ghi   jkl " on " "
(abc)
(def)
(ghi)
(jkl)
Splitting "  abc; def  ;ghi  ; jkl; " on ";"
(abc)
(def)
(ghi)
(jkl)
查看更多
登录 后发表回答