Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This method checks if a String contains a <em>special character</em> (based on your definition).</p> <pre><code>/** * Returns true if s contains any character other than * letters, numbers, or spaces. Returns false otherwise. */ public boolean containsSpecialCharacter(String s) { return (s == null) ? false : s.matches("[^A-Za-z0-9 ]"); } </code></pre> <p>You can use the same logic to count special characters in a string like this:</p> <pre><code>/** * Counts the number of special characters in s. */ public int getSpecialCharacterCount(String s) { if (s == null || s.trim().isEmpty()) { return 0; } int theCount = 0; for (int i = 0; i &lt; s.length(); i++) { if (s.substring(i, 1).matches("[^A-Za-z0-9 ]")) { theCount++; } } return theCount; } </code></pre> <p>Another approach is to put all the special chars in a String and use <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#contains%28java.lang.CharSequence%29">String.contains</a>:</p> <pre><code>/** * Counts the number of special characters in s. */ public int getSpecialCharacterCount(String s) { if (s == null || s.trim().isEmpty()) { return 0; } int theCount = 0; String specialChars = "/*!@#$%^&amp;*()\"{}_[]|\\?/&lt;&gt;,."; for (int i = 0; i &lt; s.length(); i++) { if (specialChars.contains(s.substring(i, 1))) { theCount++; } } return theCount; } </code></pre> <p><strong><em>NOTE</em></strong>: You must escape the <em>backslash</em> and <code>"</code> character with a <em>backslashes</em>. </p> <hr> <p>The above are examples of how to approach this problem in general.</p> <p>For your exact problem as stated in the question, the answer by @LanguagesNamedAfterCoffee is the most efficient approach.</p>
 

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