[java] How to trim white space from all elements in array?

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!

This question is related to java arrays string

The answer is


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


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)

For those (like me) who was looking for the same solution in Kotlin and were pointed to Java only - how to trim in Kotlin:

fun main(args: Array<String>) {
    // array definition
    val array = arrayListOf<String>(" String", "Tom Selleck "," Fish ")
    println(array) // print original -> [ String, Tom Selleck ,  Fish ]

    // remove leading and trailing spaces, result is arrayList
    val sol1 = array.map { it.trim() }
    println("sol1 = $sol1") // -> sol1 = [String, Tom Selleck, Fish]

    // remove leading and trailing spaces, result is String
    val sol2 = array.joinToString { it.trim() }
    println("sol2 = $sol2") // -> sol2 = String, Tom Selleck, Fish
}

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.


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);

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.


String val = "hi hello prince";
String arr[] = val.split(" ");

for (int i = 0; i < arr.length; i++)
{   
     System.out.print(arr[i]);
}

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


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript