Backend/Java

[StringUtills] String의 null / 빈 값 / 공백 처리하기

호_두씨 2023. 2. 27. 15:18

String의 null과 빈 값(””)처리

null이나 빈 값이 들어올때 어떻게 처리해야하는지 고민했다.

 

String의 값이 어떤 값이 들어올때 처리를 안해주는지 정의해준다.

  1. null
  2. 빈 값(””)
  3. white space
//1.
String name=null; //널
System.out.println(name==null); //true

//2.
String name2=""; //빈 값
String name3=" "; //공백
System.out.println(name2.isEmpty()); //true
System.out.println(name2.equals("")); //true
System.out.println(name3.isEmpty()); //false

System.out.println(name3.trim().isEmpty()); //true
System.out.println(StringUtils.hasText(name3)); //false

 

빈 값 처리 방법

빈 값은 isEmpty() 또는 equals()를 이용한다. 하지만 equals()가 내부적으로 가지는 여러 로직에 의해 기능적으로 낭비이다.

참고)

public boolean isEmpty() {
    return value.length == 0;
}

 

공백 처리 방법

- 공백은 isEmpty()로는 판별이 안되기 때문에 trim()을 이용해서 공백을 전부 제거한뒤 isEmpty()를 사용한다.

 

- StringUtills 클래스 이용

import org.springframework.util.StringUtils;

StringUtils의 hasText()메소드를 이용한다.

내부를 자세히 보면

public static boolean hasText(@Nullable String str) {
	return (str != null && !str.isEmpty() && containsText(str));
}

null과 빈 값을 같이 처리하고 있다. containsText() 함수를 자세히 보자

private static boolean containsText(CharSequence str) {
	int strLen = str.length();
	for (int i = 0; i < strLen; i++) {
		if (!Character.isWhitespace(str.charAt(i))) {
			return true;
		}
	}
	return false;
}

containsText()에서 공백처리를 해준다.

결론

StringUtills의 hasText()로 null과 빈 값,공백 처리를 한꺼번에 하자.

[프로젝트에서 사용한 코드]

ChallengeExplanation challengeExplanation = challenge.getExplanation();

if (StringUtils.hasText(title)) {
	challengeExplanation.setTitle(title);
}

번외

List가 null일때 isEmpty()를 사용하면 NPE 발생한다.

그러므로 null 추가하는 로직 추가해준다.

주의할 점은 null을 먼저 체크해준다.

[프로젝트에서 사용한 코드]

if (contentList != null && !contentList.isEmpty()) {
	challengeExplanation.setContents(challengeExplanationContentList);
}