문자열 앞, 뒤의 공백만 제거하는 방법입니다.

1. trim()

String.trim()은 문자열의 앞, 뒤 공백만 제거하고 가운데 공백은 제거하지 않습니다.

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

        String str = " A - B - C ";

        String result = str.trim();
        System.out.println("[" + result + "]");
    }
}

Output:

[A - B - C]

2. strip(), stripLeading(), stripTrailing()

아래와 같은 strip 함수들이 있으며, 제거하는 공백은 다음과 같습니다.

  • String.strip() : 문자열 앞, 뒤 공백 제거
  • String.stripLeading() : 문자열 앞 공백 제거
  • String.stripTrailing() : 문자열 뒤 공백 제거
public class Example {
    public static void main(String[] args) {

        String str = " A - B - C ";

        String result = str.strip();
        System.out.println("[" + result + "]");

        result = str.stripLeading();
        System.out.println("[" + result + "]");

        result = str.stripTrailing();
        System.out.println("[" + result + "]");
    }
}

Output:

[A - B - C]
[A - B - C ]
[ A - B - C]