DpATe 26
DpATe 26

Reputation: 23

Removing white space from an array containing String in Java

So how can I remove a space(s) from an array of a string...

Taking an example, I have a string called list:

String[] list ={"Apple ", "Mel on", " Ice -cream ", Television"};

Can anyone please guide on what methods I should be using? I've already tried using .replace().

Upvotes: 2

Views: 3913

Answers (2)

Yousaf
Yousaf

Reputation: 29282

Use the trim() method

String s1="  hello string   ";  
System.out.println(s1.trim()); 

EDIT

trim() method only removes leading and trailing white spaces. If you want to remove spaces between words like Mel on, you can use the replaceAll() method.

public static void main(String[] args) {
        
    String[] list ={"Apple ",  "Mel on", "  Ice -cream ", "Television"};
        
    for (int i = 0; i < list.length; i++) {
            list[i] = list[i].replaceAll(" ", "");
    }
        
    for (int i = 0; i < list.length; i++) {
           System.out.println(list[i]);
    }
}

Output

Apple
Melon
Ice-cream
Television

Upvotes: 3

Malt
Malt

Reputation: 30285

For a single string:

String str = "look!   Spaces!  ";
System.out.println(str.replaceAll(" ","")); //Will print "look!Spaces!"

For an array:

String[] arr = ...
for (int i = 0; i < arr.length; i++) {
    arr[i] = arr[i].replaceAll(" ", "");
}

Or using Java 8 streams (although this one returns a List, not an array):

String[] arr = ...
List<String> l = Arrays.stream(arr).map(i -> i.replaceAll(" ", "")).collect(Collectors.toList());

Upvotes: 5

Related Questions