I have a string that should contain only specific characters: {}()[]
I've created a validate method that checks if the string contains forbidden characters (by forbidden characters I mean everything that is not {}()[]
)
Here is my code:
private void validate(String string) {
char [] charArray = string.toCharArray();
for (Character c : charArray) {
if (!"{}()[]".contains(c.toString())){
throw new IllegalArgumentException("The string contains forbidden characters");
}
}
}
I'm wondering if there are better ways to do it since my approach doesn't seem right.
If I took the way you implement this, I would personally modify it like below:
private static void validate(String str) {
for (char c : str.toCharArray()) {
if ("{}()[]".indexOf(c) < 0){
throw new IllegalArgumentException("The string contains forbidden characters");
}
}
}
The changes are as follows:
- Not declaring a temporary variable for the
char
array. Using
indexOf
to find a character instead of convertingc
toString
to use.contains()
.Looping on the primitive
char
since you no longer needtoString()
.Not naming the parameter
string
as this can cause confusion and is not good practice.
Note: contains
calls indexOf()
, so this does also technically save you a method call each iteration.