본문 바로가기

개발/JAVA

[Spring] StringUtils 사용법

반응형

Spring에서 문자열을 다룰 때 유용하게 사용할 수 있는 유틸리티 클래스인 `StringUtils`에 대해 알아보겠습니다. 이 클래스는 문자열을 처리하는 다양한 기능을 제공하여, 코드의 가독성을 높이고 반복적인 문자열 작업을 쉽게 처리할 수 있게 돕습니다.

1. StringUtils란?

StringUtils는 Spring Framework에서 제공하는 문자열 관련 유틸리티 클래스입니다. 이 클래스는 Apache Commons Lang의 `StringUtils`를 사용하므로, 문자열의 길이나 공백 처리, 대소문자 변환 등 자주 사용되는 문자열 작업들을 손쉽게 할 수 있습니다.

2. StringUtils 주요 메서드

Spring에서 제공하는 `StringUtils`의 주요 메서드는 다음과 같습니다:

  • isEmpty(): 문자열이 비어있는지 확인
  • hasText(): 문자열에 텍스트가 있는지 확인
  • isNotEmpty(): 문자열이 비어있지 않은지 확인
  • trimWhitespace(): 문자열의 양쪽 공백을 제거
  • countOccurrencesOf(): 특정 문자가 문자열에 몇 번 등장하는지 확인

3. 예제 코드

3.1. isEmpty() 사용법

문자열이 비어 있는지 확인하려면 `isEmpty()` 메서드를 사용합니다. 이 메서드는 문자열이 null이거나 빈 문자열일 경우 `true`를 반환합니다.

import org.springframework.util.StringUtils;
public class StringUtilsExample {
public static void main(String[] args) {
String str = "";
boolean result = StringUtils.isEmpty(str);
System.out.println("isEmpty: " + result); // true
}
}

3.2. hasText() 사용법

문자열이 비어 있지 않고 텍스트가 포함되어 있는지 확인하려면 `hasText()` 메서드를 사용합니다. 이 메서드는 문자열에 공백만 포함된 경우에도 `false`를 반환합니다.

import org.springframework.util.StringUtils;
public class StringUtilsExample {
public static void main(String[] args) {
String str = " "; // 공백만 있는 문자열
boolean result = StringUtils.hasText(str);
System.out.println("hasText: " + result); // false
}
}

3.3. isNotEmpty() 사용법

문자열이 비어 있지 않은지 확인하려면 `isNotEmpty()` 메서드를 사용합니다. `isEmpty()`의 반대 기능을 합니다.

import org.springframework.util.StringUtils;
public class StringUtilsExample {
public static void main(String[] args) {
String str = "Hello, World!";
boolean result = StringUtils.isNotEmpty(str);
System.out.println("isNotEmpty: " + result); // true
}
}

3.4. trimWhitespace() 사용법

문자열의 양쪽에 있는 공백을 제거하려면 `trimWhitespace()` 메서드를 사용합니다. 문자열 앞뒤의 공백을 자동으로 잘라냅니다.

import org.springframework.util.StringUtils;
public class StringUtilsExample {
public static void main(String[] args) {
String str = " Hello, World! ";
String trimmedStr = StringUtils.trimWhitespace(str);
System.out.println("trimWhitespace: '" + trimmedStr + "'"); // 'Hello, World!'
}
}

3.5. countOccurrencesOf() 사용법

문자열에서 특정 문자가 몇 번 등장하는지 세려면 `countOccurrencesOf()` 메서드를 사용합니다.

import org.springframework.util.StringUtils;
public class StringUtilsExample {
public static void main(String[] args) {
String str = "Hello, World!";
int count = StringUtils.countOccurrencesOf(str, "o");
System.out.println("countOccurrencesOf: " + count); // 2
}
}

4. 결론

Spring의 `StringUtils`는 문자열을 다룰 때 매우 유용한 메서드들을 제공합니다. 이 클래스를 사용하면 문자열에 대한 다양한 작업을 간편하게 처리할 수 있으며, 코드의 가독성과 유지보수성을 높일 수 있습니다. 자주 사용하는 문자열 작업을 할 때 `StringUtils`를 활용해 보세요!

반응형