Java String with only letters or digits

Introduction

Checks if the String contains only unicode letters or digits.

isAlphanumeric(null)   = false
isAlphanumeric("")     = true
isAlphanumeric("  ")   = false
isAlphanumeric("abc")  = true
isAlphanumeric("ab c") = false
isAlphanumeric("ab2c") = true
isAlphanumeric("ab-c") = false
public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "demo2s.com";
        System.out.println(isAlphanumeric(str));
    }//www  .  j  a v a 2s  .c  o m
    public static boolean isAlphanumeric(String str) {
        if (str == null) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (Character.isLetterOrDigit(str.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }
}



PreviousNext

Related