Programming Tips - Java: Write an ispunct() in Java

Date: 2012may23 Update: 2025sep29 Language: Java Q. Java: Write an ispunct() in Java A. Here's one way:
class Demo { static boolean isPunct(final char c) { final int val = (int)c; return val >= 33 && val <= 47 || val >= 58 && val <= 64 || val >= 91 && val <= 96 || val >= 123 && val <= 126; // We could use Character.getType() but I don't really trust it. // This is simple and works for ASCII values. // Of course, this does not work work for international characters. } public static final void main(String []args) { { var c = 'A'; System.out.println("is '" + c + "' punct=" + isPunct(c)); } { var c = '*'; System.out.println("is '" + c + "' punct=" + isPunct(c)); } { var c = '@'; System.out.println("is '" + c + "' punct=" + isPunct(c)); } { var c = ' '; // Space System.out.println("is '" + c + "' punct=" + isPunct(c)); } } }
Output:
is 'A' punct=false is '*' punct=true is '@' punct=true is ' ' punct=false
Since ASCII isn't going to change it doesn't seem so bad to use hardcoded numbers. More info http://man-ascii.com