I am working on a java project and was wondering how I could use a string to determine whether or not the chars in an array are valid. The given string is final String ALLOWED_CHARS = "01"
.
Say I have 2 char arrays:
char[] valid = {0,0,1,0,0,0,1,1,0,1}
char[] invalid = {0,0,1,0,0,A,1,1,0,1}
What would be an efficient way of determining valid and invalid arrays using the ALLOWED_CHARS
string? I assume I am going to need to loop through the array and somehow compare each char to the chars in ALLOWED_CHARS
but I'm not sure how to go about doing it.
CodePudding user response:
You could form strings from the input character arrays and then use String#matches
along with a regex pattern.
final String ALLOWED_CHARS = "01";
String regex = "[" ALLOWED_CHARS "] ";
char[] valid = {'0', '0', '1', '0', '0', '0', '1', '1', '0', '1'};
char[] invalid = {'0', '0', '1', '0', '0', 'A', '1', '1', '0', '1'};
String s1 = new String(valid);
String s2 = new String(invalid);
System.out.println(s1 " valid? " s1.matches(regex));
System.out.println(s2 " valid? " s2.matches(regex));
This prints:
0010001101 valid? true
00100A1101 valid? false
CodePudding user response:
import java.util.*;
import java.util.stream.*;
class Main {
static final String ALLOWED_CHARS = "01";
public static void main(String[] args) {
char[] valid = {'0','0','1','0','0','0','1','1','0','1'};
char[] invalid = {'0','0','1','0','0','A','1','1','0','1'};
Set<Character> set = ALLOWED_CHARS.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.toSet());
isValid(set, valid);
isValid(set, invalid);
}
public static void isValid(Set<Character> set, char[] array) {
for (char c: array) {
if (!set.contains(c)) {
System.out.println("Invalid");
return;
}
}
System.out.println("Valid");
}
}
Another approach (other than regex) — add the ALLOWED_CHARS
to a Set
and simple check if any element in the array is not present in the Set
.