본문 바로가기
Baeldung번역&공부/Java-string

공백을 지우는 여러 방법들(Remove Whitespace From a String in Java)

by ms727 2025. 2. 7.

원본 글: https://www.baeldung.com/java-string-remove-whitespace

Java에서 String객체를 다루다보면 문자열에 존재하는 공백들을 지워야할 때가 있습니다.
이 글에서는 해당 문제를 해결할 수 있는 여러방법에 대해 다룹니다.

1. Introduction to the Problem

String myString = "   I    am a    wonderful String     !   ";

이런 예제가 있다고 생각합시다.
공백들이 글자사이에도 있고 맨 뒤에도 있고 앞에도 있습니다.
위의 경우 2가지 요구사항에 직면하게 됩니다.

  1. 모든 공백을 지워야하는 경우 -> "IamwonderfulString!"
  2. 연속공백을 하나의 공백으로 바꾸고 맨 앞, 맨 뒤 공백은 지워야하는경우 -> "I am a wonderful String !"

이 경우, String클래스에 있는 replaceAll() 함수를 사용하거나 Apache Commons 라이브러리에 있는 StringUtils클래스를 사용하는 2가지의 해결방법이 있습니다.

2. Removing All Whitespace From a String

2.1 Using String.replaceAll()

첫째로 raplceAll() 함수를 통해서 문자열의 공백들을 제거합니다.
해당 함수는 정규표현식을 통해서도 작동되는데, '\s' 문자열을 통해서 공백 문자를 찾을 수 있습니다.
replaceAll()함수와 정규표현식을 통해 공백 문자를 빈 문자열로 바꿀 수 있습니다.

public class RemoveWhitespaceTest {

    String myString = "   I    am a    wonderful String     !   ";

    @Test
    public void replace_all_whitespace_test() {
        String result = myString.replaceAll("\\s", "");
        Assertions.assertEquals("IamawonderfulString!", result);
    }
}

다음으로는 Apache Commons Lang3 라이브러리를 사용한 방법을 보겠습니다.

2.2 Using the Apache Commons Lang3 Library

Apache Commons Lang3 라이브러리는 StirngUtils 라는 유틸 클래스를 제공합니다. 다른 글의 예제에서도 많이 등장하듯 문자열을 조작하기 위한 편리한 기능들을 많이 제공하고 있습니다.

//의존성
implementation 'org.apache.commons:commons-lang3:3.17.0'

의존성을 추가하고, 해당 유틸클래스가 제공하는 deleteWhitespace() 함수를 사용하여 공백들을 제거해봅니다.
해당 함수는 모든 공백들을 제거합니다.

    @Test
    public void remove_whitespace_apache_commons_test() {
        String result = StringUtils.deleteWhitespace(myString);
        Assertions.assertEquals("IamawonderfulString!", result);
    }

3. Replacing Consecutive Whitespace Characters With One Single Space

3.1 Using String.replaceAll()

2가지 문제중 한 개의 문제는 Section2에서 해결하였습니다. 이제 다른 문제를 풀어보겠습니다.
그 전에 2가지 절차를 밟아야합니다.

  1. 연속된 공백들 1개의 공백으로 치환
  2. 문자열 앞 뒤 공백들을 제거

두 개의 순서는 상관없습니다. 문자열 앞 뒤 공백들을 먼저 제거 한 뒤, 연속된 공백들을 1개의 공백으로 치환해도 됩니다.
먼저, 첫 번째 절차(연속된 공백들 1개의 공백으로 치환)을 진행하려면 replaceAll() 함수를 통하여 하나의 공백으로 맞춰줍니다.
정규표현식의 '\s+' 는 하나 이상의 공백들을 의미합니다. 그렇기에 replaceAll("\\s+"," ") 구문을 통하여 첫 번째 절차를 수행합니다. 그리고 String.trim() 함수를 사용하여 앞 뒤 공백을 제거합니다.

    @Test
    public void remove_whitespace_one_single_space_test() {
        String result = myString.replaceAll("\\s+", " ");
        Assertions.assertEquals(" I am a wonderful String ! ", result);
        Assertions.assertEquals("I am a wonderful String !", result.trim());
    }

두 절차를 모두 테스트해보았습니다.

3.2 Using the Apache Commons Lang3 Library

다음은 Apache Commons Lang3 라이브러리를 통하여 문자열을 제거해봅니다. StringUtils.normalizeSpace() 함수를 통해 들어온 문자열에 대해 앞 뒤 공백 제거 및 연속된 공백을 하나의 공백으로 치환해줍니다.

    @Test
    public void remove_whitespace_one_single_space_test() {
        String result = myString.replaceAll("\\s+", " ");
        Assertions.assertEquals(" I am a wonderful String ! ", result);
        Assertions.assertEquals("I am a wonderful String !", result.trim());
    }

추가 의견: 해당 함수가 저 2가지 기능만 수행하는지, 또 어떻게 동작하는지 궁금하여 찾아봤습니다.

public static String normalizeSpace(String str) {
        if (isEmpty(str)) {
            return str;
        } else {
            int size = str.length();
            char[] newChars = new char[size];
            int count = 0;
            int whitespacesCount = 0;
            boolean startWhitespaces = true;

            for(int i = 0; i < size; ++i) {
                char actualChar = str.charAt(i);
                boolean isWhitespace = Character.isWhitespace(actualChar);
                if (isWhitespace) {
                    if (whitespacesCount == 0 && !startWhitespaces) {
                        newChars[count++] = " ".charAt(0);
                    }

                    ++whitespacesCount;
                } else {
                    startWhitespaces = false;
                    newChars[count++] = actualChar == 160 ? 32 : actualChar;
                    whitespacesCount = 0;
                }
            }

            if (startWhitespaces) {
                return "";
            } else {
                return (new String(newChars, 0, count - (whitespacesCount > 0 ? 1 : 0))).trim();
            }
        }
    }

내부 구현은 이렇게 되어있습니다.
빈 문자열인지 확인하고, 공백으로만들어온 경우 아닌 경우를 확인하여 로직을 진행합니다.
꽤나 단순하게 문자열을 Loop돌면서 새로운 문자열을 구성하고 있습니다.


4. Remove Only Leading and Trailing Whitespace

4.1 Using strip()

strip() 함수는 문자열의 앞 뒤 공백을 지워주는 용도로 사용됩니다. 이 함수는 Java11버전 이상부터 제공되고 있고 기존 ASCII 코드의 공백만을 제거하던 trim() 함수보다 좀 더 Unicode를 잘 인식합니다.

    @Test
    public void remove_whitespace_strip_test() {
        String result = myString.strip();
        Assertions.assertEquals("I    am a    wonderful String     !", result);
    }

테스트를 진행해보면 문자열 맨 앞,뒤 공백은 잘 제거하지만 단어 사이의 공백은 못 지우는걸 확인할 수 있습니다.

4.2 Using stripLeading() and stripTrailing()

Java11이상부터는 stripLeading(), stripTrailing() 함수를 제공합니다. 두 함수는 각각 맨 앞이나 맨 뒤의 공백들을 제거합니다.

    @Test
    public void stripLeading_stripTrailing_test() {
        Assertions.assertEquals("I    am a    wonderful String     !   ", myString.stripLeading());
        Assertions.assertEquals("   I    am a    wonderful String     !", myString.stripTrailing());
    }

5. 결론

공백을 지우는 여러 방법에 대해 학습하였습니다.


역시나 너무나도 강력한 Apache Common Library.. 글을 작성하다보면 이 라이브러리 없이 문자열 조작하긴 힘들지 않을까 했습니다. 대부분이 null-safe, 빈문자열 검증을 한다는게 가장 큰 장점이 아닐까 합니다.

문자열을 지울때 Apache common 라이브러리를 사용하고, 앞이나 뒤만 지워야한다면 String.strip~()함수를 사용하지 않을까합니다.