1

i'm trying to check how many non-alphanumeric characters can be found on a string for example:

String message = "i'm a keyboard!!!"

i want to check how many "!" and " ' " can be found on that string, not only those, but any symbol.

Kyozumo
  • 23
  • 1
  • 4
  • What have you tried? Perhaps replacing all alphanumeric characters with nothing and testing the length of the result? – Anders R. Bystrup Jun 30 '14 at 19:35
  • Iterate through the string and count them... – jhobbie Jun 30 '14 at 19:35
  • 3
    use Regex.. with them, you will be able to get the required result in less time.. – Shrikant Kakani Jun 30 '14 at 19:36
  • Not an exact duplicate, but plenty of ideas: [Java regex: check if word has non alphanumeric characters](http://stackoverflow.com/questions/5506154/java-regex-check-if-word-has-non-alphanumeric-characters?rq=1) – PM 77-1 Jun 30 '14 at 19:40
  • Have an array of symbols, then iterate your your String, if it's equal to any of the symbols in the array, increment count – Juxhin Jun 30 '14 at 19:41

1 Answers1

4

Regular expressions would be good for this. Try just replacing alphanumeric character with nothing and taking the length.

pattern = "[a-zA-Z0-9]*"
newString = message.replaceAll(pattern, "")
return newString.length
Philip Massey
  • 1,401
  • 3
  • 14
  • 24
  • 1
    If you also include underscore as an alphanumeric, you can use `String pattern = "\\w";` instead. – Keppil Jun 30 '14 at 19:46