21

Here's what I have:

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

I want to write something to the effect of:

if(!charArray contains 'q'){
     break;
}

I realize that .contains() can't be used here. I am just using "contains" to illustrate what I'm trying to do.

Aei
  • 677
  • 6
  • 11
  • 17
  • possible duplicate of [In Java, how can I test if an Array contains a certain value?](http://stackoverflow.com/questions/1128723/in-java-how-can-i-test-if-an-array-contains-a-certain-value) – Aaron Sep 02 '13 at 22:41
  • 5
    @Aaron: No, you can't use `Arrays.asList()` for **primitive** arrays. – jlordo Sep 02 '13 at 23:15

7 Answers7

36

The following snippets test for the "not contains" condition, as exemplified in the sample pseudocode in the question. For a direct solution with explicit looping, do this:

boolean contains = false;
for (char c : charArray) {
    if (c == 'q') {
        contains = true;
        break;
    }
}
if (!contains) {
    // do something
}

Another alternative, using the fact that String provides a contains() method:

if (!(new String(charArray).contains("q"))) {
    // do something
}

Yet another option, this time using indexOf():

if (new String(charArray).indexOf('q') == -1) {
    // do something
}
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • The logic seems backwards; OP wants to break when the character is _not_ in the character array. Not a biggie for alternatives 2 and 3 (just reverse the sense of the tests), but option 1 would need a little make-over. – Ted Hopp Sep 03 '13 at 22:52
  • @TedHopp agreed, edited to reflect OP's sample pseudocode. The question is confusing, the title asks how to determine "if a char array contains a particular character", but the sample code implies a "not contains" situation – Óscar López Sep 03 '13 at 22:58
7

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...
}
ceklock
  • 6,143
  • 10
  • 56
  • 78
4

You can iterate through the array or you can convert it to a String and use indexOf.

if (new String(charArray).indexOf('q') < 0) {
    break;
}

Creating a new String is a bit wasteful, but it's probably the tersest code. You can also write a method to imitate the effect without incurring the overhead.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • He has used falsy condition. – Rohit Jain Sep 02 '13 at 22:39
  • @mikeyaworski - No, I think I mean `< 0`. OP wants to break if the character is _not_ in the character array. – Ted Hopp Sep 02 '13 at 23:20
  • @mikeyaworski - No. If `q` is not in the string, then `indexOf` will return -1, which is when OP wants to break. Look at OP's question; there's a `!` operator in front of the test. – Ted Hopp Sep 02 '13 at 23:33
4

Some other options if you do not want your own "Utils"-class:

Use Apache commons lang (ArrayUtils):

@Test
public void arrayCommonLang(){
    char[] test = {'h', 'e', 'l', 'l', 'o'};
    Assert.assertTrue(ArrayUtils.contains(test, 'o'));
    Assert.assertFalse(ArrayUtils.contains(test, 'p'));
}

Or use the builtin Arrays:

@Test
public void arrayTest(){
    char[] test = {'h', 'e', 'l', 'l', 'o'};
    Arrays.sort(test);
    Assert.assertTrue(Arrays.binarySearch(test, 'o') >= 0);
    Assert.assertTrue(Arrays.binarySearch(test, 'p') < 0);
}

Or use the Chars class from Google Guava:

@Test
public void testGuava(){
    char[] test = {'h', 'e', 'l', 'l', 'o'};
    Assert.assertTrue(Chars.contains(test, 'o'));
    Assert.assertFalse(Chars.contains(test, 'p'));
}

Slightly off-topic, the Chars class allows to find a subarray in an array.

Az.MaYo
  • 1,044
  • 10
  • 23
beat
  • 1,857
  • 1
  • 22
  • 36
  • 3
    `binarySearch` when the array is not sorted returns an undefined result (https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(char[],%20char)) – Nicolas Henneaux Mar 12 '19 at 07:30
  • CAUTION: The array must be sorted (as by the sort(char[]) method) prior to making Arrays.binarySearch() call. – prash Aug 15 '19 at 13:04
3

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.

Ryan
  • 712
  • 7
  • 21
0

From NumberKeyListener source code. This method they use to check if char is contained in defined array of accepted characters:

protected static boolean ok(char[] accept, char c) {
    for (int i = accept.length - 1; i >= 0; i--) {
        if (accept[i] == c) {
            return true;
        }
    }

    return false;
}

It is similar to @ÓscarLópez solution. Might be a bit faster cause of absence of foreach iterator.

arenaq
  • 2,304
  • 2
  • 24
  • 31
-1

You can also define these chars as list of string. Then you can check if the characters is valid for accepted characters with list.Contains(x) method.

Erkan Ceylan
  • 19
  • 1
  • 5