In Java, how can I determine if a char array contains a particular character?

后端 未结 7 1539
野趣味
野趣味 2020-12-05 18:53

Here\'s what I have:

char[] charArray = new char[] {\'h\',\'e\',\'l\',\'l\',\'o\'};

I want to write something to the effect of:

<         


        
相关标签:
7条回答
  • 2020-12-05 19:50

    This method does the trick.

    boolean contains(char c, char[] array) {
        for (char x : array) {
            if (x == c) {
                return true;
            }
        }
        return false;
    }
    

    Example of usage:

    class Main {
    
        static boolean contains(char c, char[] array) {
            for (char x : array) {
                if (x == c) {
                    return true;
                }
            }
            return false;
        }
    
        public static void main(String[] a) {
            char[] charArray = new char[] {'h','e','l','l','o'};
            if (!contains('q', charArray)) {
                // Do something...
                System.out.println("Hello world!");
            }
        }
    
    }
    

    Alternative way:

    if (!String.valueOf(charArray).contains("q")) {
        // do something...
    }
    
    0 讨论(0)
提交回复
热议问题