StringUtils 클래스 이해하기

이번 시간에는 Apache Commons Lang 컴포넌트의 StringUtils 클래스에 대해 살펴보겠다. StringUtils 클래스는 말 그대로 문자열을 손쉽게 다룰 수 있도록 도우미 메소드를 모아놓은 클래스이다. 또 하나 유용한 것은 null에 안전하다는 것이다.

좀 유용하다 싶은 것들로 예제를 작성해보았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
// abbreviate 메소드는 문장을 축약하는 기능을 제공한다.
// 게시판 제목을 줄일 때 사용하면 좋을 듯 하다.
System.out.println(StringUtils.abbreviate("Hello world!", 5));
System.out.println(StringUtils.abbreviate("Hello", 5));
// capitalize 메소드는 문장의 첫 글자를 대문자로 만드는 기능을 제공한다.
// 워드 프로세서에서 자주 사용되는 기능이다.
System.out.println(StringUtils.capitalize("hello world!"));
// center 메소드는 문장을 가운데 정렬하는 기능을 제공한다.
System.out.println(StringUtils.center("Hello world!", 20));
System.out.println(StringUtils.center("Hello world!", 20, '*'));
// containsAny 메소드는 해당 문장에 포함된 문자나 문자열이 있는지 판단한다.
// 예제처럼 가변인자로도 받을 수 있다.
System.out.println(StringUtils.containsAny("Hello world!", 'a', 'b', 'c', 'd'));
System.out.println(StringUtils.containsAny("Hello world!", 'a', 'b', 'c'));
// join 메소드는 각 문자열 사이에 문자나 문자열을 집어넣는 기능을 제공한다.
// 예제로 전화번호 사이의 하이픈을 넣어보았다.
System.out.println(StringUtils.join(new String[] { "010", "1234", "4567" }, '-'));
// repeat 메소드는 해당 문자열을 반복해주는 기능을 제공한다.
// 패스워드가 저장된 이후 접속 시 사용하면 유용할 듯하다.
System.out.println(StringUtils.repeat('*', 5));
}
}

실행 결과이다.

1
2
3
4
5
6
7
8
He...
Hello
Hello world!
Hello world!
****Hello world!****
true
false
010-1234-4567

이 밖에도 다양한 기능들이 있지만 너무 많기도 많고 메소드들이 너무 직관적이라 구지 더 설명할 필요가 없을 듯하다. 다른 메소드들도 사용해보기 바란다.

Share Comments