How to trim white space from all elements in array?
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();
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.