Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would prefer not to use <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#trim%28%29" rel="noreferrer">String.trim</a> to check for existence of whitespace. It is doing more work than you need, since it checks both ends of the string (even if non-whitespace was found at the other end) AND it returns a new String object. So I would prefer to implement a method to check for whitespace only.</p> <p>So my suggestion (if implementing yourself) would be as follows:</p> <pre><code>public static boolean isNullOrEmpty(String s) { return s == null || s.length() == 0; } public static boolean isNullOrWhitespace(String s) { return s == null || isWhitespace(s); } private static boolean isWhitespace(String s) { int length = s.length(); if (length &gt; 0) { for (int i = 0; i &lt; length; i++) { if (!Character.isWhitespace(s.charAt(i))) { return false; } } return true; } return false; } </code></pre> <p>Or taking a cue from String.trim's implementation, you could use character comparison rather than Character.isWhitespace():</p> <pre><code>// checking for whitespace like String.trim() does private static boolean isWhitespace(String s) { int length = s.length(); if (length &gt; 0) { for (int i = 0; i &lt; length; i++) { if (s.charAt(i) &gt; ' ') { return false; } } return true; } return false; } </code></pre> <p>Finally, I'd consider checking both ends of the string in each iteration, stepping inwards. This would minimize the number of iterations needed to get the answer, regardless of whether whitespace exists at the front or the end of the string.</p> <pre><code>private static boolean isWhitespace(String s) { int length = s.length(); if (length &gt; 0) { for (int start = 0, middle = length / 2, end = length - 1; start &lt;= middle; start++, end--) { if (s.charAt(start) &gt; ' ' || s.charAt(end) &gt; ' ') { return false; } } return true; } return false; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload