I Spy Code - Java

Check if string has ASCII printable characters

Question:

Write a java program that checks if a string contains only ASCII printable characters.

Solution:

Here is a java example that verifies if a string only has ASCII printable characters:

Source: (Example.java)

import org.apache.commons.lang.StringUtils;
 
public class Example {
 
   public static void main(String[] args) {
 
      String str1 = "the cat in the hat";
      String str2 = "the \n cat in the hat";
      String str3 = "the cat in \u007f the hat";
 
      System.out.println(StringUtils.isAsciiPrintable(str1));
      System.out.println(StringUtils.isAsciiPrintable(str2));
      System.out.println(StringUtils.isAsciiPrintable(str3));
   }
}
 

Output:

$ java Example
true
false
false

References:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isAsciiPrintable-java.lang.CharSequence-

Questions answered by this page:

Java example that tests if a string contains only ASCII printable characters.