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!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With