HOWTO · Java

Java의 trim() 대 strip()

이 자습서에서는 Java에서 trim() 및 strip() 메서드의 차이점을 보여줍니다.

이 페이지의 내용

이 튜토리얼은 Java의 trim()strip() 메소드 간의 차이점을 보여줍니다.

자바 trim()strip()

trim()strip() 메서드는 모두 문자열 유형 데이터에 사용되며 어떻게든 동일한 작업을 수행합니다. 두 방법 모두 문자열에서 후행 및 선행 공백을 제거합니다.

그러나 두 방법 모두 몇 가지 차이점이 있습니다. 아래 표는 trim()strip() 메소드 간의 차이점을 보여줍니다.

trim() strip()
trim() 메서드는 JDK 버전 10부터 추가되었습니다. strip() 메서드는 JDK 버전 11부터 추가되었습니다.
trim() 메소드는 항상 새 문자열 객체를 할당합니다. strip() 메서드는 스트립핑을 빈 문자열로 최적화한 다음 인턴된 String 상수를 반환합니다.
trim()은 공백 문자의 코드 포인트가 U+0020보다 작거나 같은 후행 및 선행 공백을 제거합니다. strip() 메서드도 후행 및 선행 공백을 제거하지만 Character.isWhitespace(int) 메서드를 사용하여 공백 문자를 결정합니다.

strip() 메서드는 유니코드 표준이므로 trim()을 사용하는 것보다 권장됩니다. trim()strip()의 사용을 보여주는 예를 살펴보겠습니다.

package delftstack;

public class Trim_Vs_Strip {
  public static void main(String[] args) {
    // case 1: simple string with trailing space
    final String DemoString1 = " www.delftstack.com ";
    System.out.println(DemoString1.trim().equals(DemoString1.strip()));
    // return --> true

    // case 2: string with leading \t and trailing \r
    final String DemoString3 = "\t www.delftstack.com \r";
    System.out.println(DemoString3.trim().equals(DemoString3.strip()));
    // return --> true

    // case 3: string the Unicode of whitespace
    final String DemoString2 = "www.delftstack.com \u2005";
    System.out.println(DemoString2.trim().equals(DemoString2.strip()));
    // return --> false

    // case 4: Unicode less than the white space.
    final String DemoString4 = "\u2001";
    System.out.println(DemoString4.trim().equals(DemoString4.strip()));
    // return --> false
  }
}

위의 코드는 다른 유형의 문자열에서 trim()strip() 메서드를 비교하고 두 메서드가 서로 다른 시나리오에서 서로 다른 방식으로 수행됨을 보여줍니다.

출력 참조:

true
true
false
false