Java String[]에서 ""를 찾아내기

2024. 11. 30. 07:48Java

기본

public class FindEmptyString {
    public static void main(String[] args) {
        String[] array = {"Hello", "World", "", "Java"};

        boolean hasEmptyString = false;
        for (String str : array) {
            if ("".equals(str)) { // Check for an empty string
                hasEmptyString = true;
                break; // Exit the loop as we found an empty string
            }
        }

        System.out.println("Contains empty string: " + hasEmptyString);
    }
}

Helper 사용

public class FindEmptyStringHelper {
    public static boolean containsEmptyString(String[] array) {
        if (array == null || array.length == 0) {
            return false; // Handle null or empty arrays
        }
        for (String str : array) {
            if ("".equals(str)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        String[] array = {"Hello", "", "World"};
        System.out.println("Contains empty string: " + containsEmptyString(array));
    }
}

List 사용

import java.util.Arrays;

public class FindEmptyStringInList {
    public static void main(String[] args) {
        String[] array = {"Hello", "", "World"};
        boolean hasEmptyString = Arrays.asList(array).contains("");

        System.out.println("Contains empty string: " + hasEmptyString);
    }
}