Remove spaces from a String array

Asked

Viewed 373 times

2

How to remove spaces (not all spaces, just the beginning and end) from all indexes of a Java String array?

2 answers

5


Using trim():

String[]  strArray = {" teste ", " teste ", " teste "};

for(int i = 0; i < strArray.length; i++){
  strArray[i]  = strArray[i].trim();
}
  • 2

    I don’t know why I didn’t think of it

  • 1

    @Felipe.rce is simple to make :)

3

in the java-8 you can just do it this way:

String[] resultado = Arrays.stream(meuArray).map(String::trim).toArray(String[]::new);

Or you can make this version more "dirty" without creating a final array, the array passed will be modified automatically

Arrays.stream(meuArray).map(String::trim).toArray(unused -> meuArray);
  • What about an array? That’s not really an array, but a list.

  • @My mistake, I was used to doing with lists, but I’ve edited!

  • I don’t know anything about Java 8, so I don’t understand it very well, but I’m going to test it here to see

Browser other questions tagged

You are not signed in. Login or sign up in order to post.