2

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().

2 Answers 2

5

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());
Sign up to request clarification or add additional context in comments.

Comments

3

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

4 Comments

that will only get rid of leading and trailing spaces
OP didn't mention if he wants to remove spaces between words but anyways will edit my answer
He gave Mel on as an example
Right... Edited my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.