Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 667
TomSelleck Avatar asked Mar 25 '12 22:03

TomSelleck


People also ask

How do you trim whitespace from all elements in an array?

Method 3: Basic method using for loop: Use for loop to traverse each element of array and then use trim() function to remove all white space from array elements.

How do you free space in an array?

Arrays don't have "free space". You can use a "magic value" (e.g. zero, or null depending on the type) to represent empty if you wish. Then you can search through the array looking for this value: int i = Array.


2 Answers

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(); 
like image 155
Óscar López Avatar answered Sep 20 '22 12:09

Óscar López


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.

like image 36
user2189998 Avatar answered Sep 20 '22 12:09

user2189998