본문 바로가기
Java

Java String 앞 또는 뒤의 공백만 제거하기.

by Dokon Jang 2021. 7. 21.
반응형

Java String 앞 또는 뒤의 공백만 제거하기.

String에서 trim 메소드를 사용하면 앞과 뒤의 모든 공백을 제거합니다.

앞 또는 뒤의 공백만 제거하는 방법입니다.

JAVA 11 이상에 앞의 공백 제거 메소드 stripLeading, 뒤의 공백 제거 메소드 stripTrailing가 추가되었습니다.

 

앞의 공백 제거하기
String str = "    ABCD      ";
str = str.stripLeading();

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#stripLeading()

 

String (Java SE 11 & JDK 11 )

Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argum

docs.oracle.com

 

뒤의 공백 제거하기
String str = "    ABCD      ";
str = str.stripTrailing();

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#stripTrailing()

 

String (Java SE 11 & JDK 11 )

Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argum

docs.oracle.com

 

참고) replaceAll에 정규식으로 뒤의 공백 제거
String str = "    ABCD      ";
str = str.replaceAll("\\s+$", "");
반응형

댓글