10
\$\begingroup\$

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!

\$\endgroup\$

2 Answers 2

7
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ It took me a while to figure out how your Verifier class works, but it's a very clever way of mapping the use of each character! \$\endgroup\$ Commented Apr 1, 2014 at 20:19
2
\$\begingroup\$

Instead of two for loops and checking the names chars with each char of VALID_CHARS i used one for..loop and check validness by checking, if the name contains the char by using the String.indexOf() method.

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

    boolean failed = false;
    for (int i = 0; !failed && i < VALID_CHARS.length; i++) {
        failed = (name.indexOf(VALID_CHARS[i]) < 0);
    }

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.