HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Checking if a string matches an array of valid characters

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
matchesarraycheckingvalidcharactersstring

Problem

I am wondering what a better solution would be for this bit of code:

public static void main( String[] args )
{
    String name = "hello, ddd";

    boolean[] success = new boolean[ name.length() ];
    for( char character: VALID_CHARS ) {
        for( int index = 0; index < name.length(); index ++ ) {
            if( name.charAt( index ) == character ) {
                success[ index ] = true;
            }
        }
    }

    boolean failed = false;
    for( boolean b: success ) {
        if( ! b ) {
            failed = true;
        }
    }

    System.out.println( "You" + ( failed ? " failed": " succeeded" ) + "." );
}


I have an array of valid characters that can be used for a name object, I want to check if each index of the string is valid, if each index is valid return true, otherwise return false. Any help / guidance is appreciated!

Solution

memory is surprisingly fast and efficient. If your string-to-test is even modestly large (like 1K), then you may find the following algorithm is efficient. This is especially efficient when the valid-character set is reusable....

boolean[] isvalid = new boolean[Character.MAX_VALUE + 1];
for (char c : VALID_CHARS) {
    isvalid[c] = true;
}
for (char c : name) {
    if (!isvalid[c]) {
       System.out.println("You failed!.");
       return;
    }
}
System.out.println("You succeeded!.");


Now, in your case, there is no reason why VALID_CHARS cannot be declared as:

private static final boolean[] VALIDCHARS = buildValidChars();
private static final boolean[] buildValidChars() {
    ....
}


I have used, and benchmarked this sort of system to great effect when building the JDOM Character validator... you can see how I did it there.... but using a bit-mask representation to use less memory.... which is a bit faster. I also put together a bit of a benchmarh and writeup for the JDOM Verifier performance.

Code Snippets

boolean[] isvalid = new boolean[Character.MAX_VALUE + 1];
for (char c : VALID_CHARS) {
    isvalid[c] = true;
}
for (char c : name) {
    if (!isvalid[c]) {
       System.out.println("You failed!.");
       return;
    }
}
System.out.println("You succeeded!.");
private static final boolean[] VALIDCHARS = buildValidChars();
private static final boolean[] buildValidChars() {
    ....
}

Context

StackExchange Code Review Q#39953, answer score: 7

Revisions (0)

No revisions yet.