study gomi

Java 문자열 빈 문자열인지 확인하기 본문

basic/java

Java 문자열 빈 문자열인지 확인하기

공부하곰 2024. 6. 5. 09:41
728x90
반응형

문자열의 길이를 확인

public class EmptyStringCheck {
    public static void main(String[] args) {
        String str = "";

        if (str.length() == 0) {
            System.out.println("The string is empty.");
        } else {
            System.out.println("The string is not empty.");
        }
    }
}

 

isEmpty() 메서드를 사용

- 가장 간단하고 직관적인 방법.

public class EmptyStringCheck {
    public static void main(String[] args) {
        String str = "";

        if (str.isEmpty()) {
            System.out.println("The string is empty.");
        } else {
            System.out.println("The string is not empty.");
        }
    }
}

 

isBlank() 메서드를 사용 (Java11 이상)

- 공백 문자열까지 확인할 때 유용

public class EmptyStringCheck {
    public static void main(String[] args) {
        String str = "   ";

        if (str.isBlank()) {
            System.out.println("The string is empty or blank.");
        } else {
            System.out.println("The string is not empty or blank.");
        }
    }
}

 

trim().isEmpty()를 사용

- trim() 메서드를 사용하여 문자열의 앞뒤 공백을 제거한 후 isEmpty() 메서드를 사용.

- 이 방법은 isBlank() 메서드와 유사한 기능을 제공.

public class EmptyStringCheck {
    public static void main(String[] args) {
        String str = "   ";

        if (str.trim().isEmpty()) {
            System.out.println("The string is empty or only contains whitespace.");
        } else {
            System.out.println("The string is not empty and has non-whitespace characters.");
        }
    }
}

 

정리

- 길이 확인 : str.length() == 0

- isEmpty() 메서드 : str.isEmpty()

- isBlank() 메서드 : str.isBlank() (Java 11 이상)

- trim().isEmpty() : str.trim().isEmpty()

728x90
반응형