String의 모든 공백을 제거하는 방법입니다.

1. String.replaceAll()

String.replaceAll(str, replacement)는 문자열에서 str에 해당하는 내용을 모두 찾아서 replacement로 변환합니다.

아래 예제에서 str.replaceAll(" ", "")는 str에서 공백(" ")을 찾고 빈 문자열("")로 변환하여 제거합니다.

public class Example {
    public static void main(String[] args) {

        String str = " A - B - C ";

        String result = str.replaceAll(" ", "");
        System.out.println(result);
    }
}

Output:

A-B-C

2. 정규표현식(Regex)

String.replaceAll(regex, replacement)는 문자열에서 regex 패턴에 해당하는 문자열을 찾고 replacement로 변환합니다.

아래 예제에서 str.replaceAll("\\s", "")는 str에서 공백을 의미하는 \\s 패턴을 찾고 빈 문자열("")로 변환하여 제거합니다.

public class Example {
    public static void main(String[] args) {

        String str = " A - B - C ";

        String result = str.replaceAll("\\s", "");
        System.out.println(result);
    }
}

Output:

A-B-C

정규표현식 패턴 \s는 공백(whitespace)을 의미합니다. 자바에서 \을 입력하려면 \\처럼 두번 입력해야해서 "\\s"가 되었습니다.