most efficient way to check if a string contains specific characters

jennifer lawrence :

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.

Nexevis :

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 converting c to String to use .contains().

  • Looping on the primitive char since you no longer need toString().

  • 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164154&siteId=1