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.
contains() method with Examples. The contains() method of Chars Class in Guava library is used to check if a specified value is present in the specified array of char values. The char value to be searched and the char array in which it is to be searched, are both taken as a parameter.
The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
contains() method in Java is used to check whether or not a list contains a specific element. To check if an element is in an array, we first need to convert the array into an ArrayList using the asList() method and then apply the same contains() method to it.
Java String indexOf() Method The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
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
}
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With