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

后端 未结 7 1661
野趣味
野趣味 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:24

    Here's a variation of Oscar's first version that doesn't use a for-each loop.

    for (int i = 0; i < charArray.length; i++) {
        if (charArray[i] == 'q') {
            // do something
            break;
        }
    }
    

    You could have a boolean variable that gets set to false before the loop, then make "do something" set the variable to true, which you could test for after the loop. The loop could also be wrapped in a function call then just use 'return true' instead of the break, and add a 'return false' statement after the for loop.

提交回复
热议问题