[Java] 문자열 공백 제거 trim, replace, strip

민지의 회고록·2023년 2월 9일

1. trim()

  • 문자열 앞 뒤 공백 제거
String str = " first and end character are blank ";
System.out.println("[" + str + "]");
System.out.println("[" + str.trim() + "]");
  • 출력
    [ first and end character are blank ][first and end character are blank]

2. replace(), replaceAll()

  • replace(a, b), replaceAll(a, b) : a를 b로 교체
  • 모든 공백 제거
String str = " first and end character are blank ";
System.out.println("[" + str + "]");
System.out.println("[" + str.replaceAll(" ", "") + "]");
  • 출력
    [ first and end character are blank ][firstandendcharacterareblank]

3. strip()

  • 문자열 앞 뒤 공백 제거
String str = " first and end character are blank ";
System.out.println("[" + str + "]");
System.out.println("[" + str.trim() + "]");
  • 출력
    [ first and end character are blank ][first and end character are blank]
  • stripLeading(), stripTrailing() : 각각 문자열의 앞, 뒤 공백을 제거

trim, strip 차이

  • trim : '\u0020' 이하 공백 제거
  • strip : 유니코드 상의 공백 제거
    (ex. 스페이스('\u0020'), 탭('\u0009))
// \u2003 == EM SPACE
String str = "\u2003first and end character are blank\u2003";
System.out.println("[" + str.trim() + "]");
System.out.println("[" + str.strip() + "]");
  • 출력
    [ first and end character are blank ][first and end character are blank]
profile
민지가 공부한 내용을 회고합니다~~

0개의 댓글