How to Remove Spaces in a String in Java

0 min read 183 words

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:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags