How to Remove Spaces in a String in Java

The challenge

Simple, remove the spaces from the string, then return the resultant string.

The solution in Java code

class Solution {
    static String noSpace(final String x) {
        return x.replace(" ", "");
    }
}

An alternative:

class Solution {
    static String noSpace(final String x) {
        return x.replaceAll("\\s+","");
    }
}

Test cases to validate our Java solution

import org.junit.Test;
import java.util.Random;
import static org.junit.Assert.assertEquals;

public class SolutionTest {
    @Test public void testSomething() {
        assertEquals("8j8mBliB8gimjB8B8jlB", Solution.noSpace("8 j 8   mBliB8g  imjB8B8  jl  B"));
        assertEquals("88Bifk8hB8BB8BBBB888chl8BhBfd", Solution.noSpace("8 8 Bi fk8h B 8 BB8B B B  B888 c hl8 BhB fd"));
        assertEquals("8aaaaaddddr", Solution.noSpace("8aaaaa dddd r     "));
        assertEquals("jfBmgklf8hg88lbe8", Solution.noSpace("jfBm  gk lf8hg  88lbe8 "));
        assertEquals("8jaam", Solution.noSpace("8j aam"));
    }
    
    private static final String chars = "abc defg hij klm no pq rstuvw xyz";

    @Test public void randomTests() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 20; i++) {
            int length = random.nextInt(15) + 1;
            for (int j = 0; j < length; j++) {
                int index = random.nextInt(chars.length());
                sb.append(chars.charAt(index));
            }
            String input = sb.toString();
            sb.setLength(0);
            assertEquals(input.replaceAll(" ", ""), Solution.noSpace(input));
        }
    }
}
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments