How to case-insensitively check if a character exists in a string with Java

1 Answer

0 votes
public class Main {

    // Convert a character to lowercase
    static char toLowerChar(char c) {
        return Character.toLowerCase(c);
    }

    // Case-insensitive check without a loop
    static boolean charExistsIgnoreCase(String s, char target) {
        return s.toLowerCase().indexOf(toLowerChar(target)) != -1;
    }

    public static void main(String[] args) {
        // Define the string we want to search in
        String s = "JavaLanguage";

        // Perform the case-insensitive check
        boolean exists = charExistsIgnoreCase(s, 'j');

        // Print the raw boolean result
        System.out.println(exists);

        // Conditional check
        if (exists) {
            System.out.println("exists");
        } else {
            System.out.println("not exists");
        }
    }
}


/*
Output:

true
exists

*/

 



answered 8 hours ago by avibootz
edited 4 hours ago by avibootz

Related questions

...