Here\'s what I have:
char[] charArray = new char[] {\'h\',\'e\',\'l\',\'l\',\'o\'};
I want to write something to the effect of:
<
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.
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'};
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.
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.
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.
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.
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
}