본문으로 바로가기

1. trim()

앞, 뒤 공백을 제거해줍니다.

'\u0020' 이하의 공백들만 제거

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {

    public String trim() {
        String ret = isLatin1() ? StringLatin1.trim(value)
                                : StringUTF16.trim(value);
        return ret == null ? this : ret;
    }
}

 

[예시]

String test = "    An apple is delicious    ";

System.out.println("'" + test + "'"); // '    An apple is delicious    '
System.out.println("'" + test.trim() + "'"); // 'An apple is delicious'

 

2. strip()

앞, 뒤 공백을 제거해줍니다.

유니코드의 공백들을 모두 제거

Since: Java 11

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {

    public String strip() {
        String ret = isLatin1() ? StringLatin1.strip(value)
                                : StringUTF16.strip(value);
        return ret == null ? this : ret;
    }
}

 

[trim() vs strip()]

trim()

: '\u0020' 이하의 공백들만 제거

 

strip()

: 유니코드의 공백들을 모두 제거

 

참조 Whitespace URL

https://en.wikipedia.org/wiki/Whitespace_character

 

[예시]

final char SPACE = '\u0020';
final char THIN_SPACE = '\u2009';

String test1 = SPACE + "  An apple is delicious  " + SPACE;
String test2 = THIN_SPACE + "  An apple is delicious  " + THIN_SPACE;

System.out.println("==test1==");
System.out.println("'" + test1 + "'");
System.out.println("'" + test1.trim() + "'");
System.out.println("'" + test1.strip() + "'");

System.out.println("==test2==");
System.out.println("'" + test2 + "'");
System.out.println("'" + test2.trim() + "'");
System.out.println("'" + test2.strip() + "'");

결과 값

 

3. 특정 위치 공백 제거( stripLeading(), stripTrailing() )

public String stripLeading() :  문자열 의 공백을 제거
public String stripTrailing() : 문자열 의 공백을 제거

String test = "    An apple is delicious    ";

System.out.println("'" + test + "'");
System.out.println("'" + test.stripLeading() + "'"); // 'An apple is delicious    '
System.out.println("'" + test.stripTrailing() + "'"); // '    An apple is delicious'

 

4. 모든 공백 제거 ( replace(), replaceAll() )

public String replace(CharSequence target, CharSequence replacement)

: target 부분을 replacement로 대치한 새로운 문자열을 리턴

 

public String replaceFirst(String regex, String replacement)

: 처음으로 만나는 부분만 대치

 

public String replaceAll(String regex, String replacement)

: 패턴(정규식)이 일치할 경우 모두 대치

 

[예시]

String test = " An apple is delicious    ";

System.out.println("'" + test + "'");
System.out.println("'" + test.replace(" ","") + "'"); // 'Anappleisdelicious'
System.out.println("'" + test.replaceFirst("\\s","") + "'"); // 'An apple is delicious    '
System.out.println("'" + test.replaceAll("\\s","") + "'"); // 'Anappleisdelicious'