0

I want to check, if my character is a special symbol or not using standard Charset (for now, I've implemented it through regex check of [^a-zA-Z0-9 ]). Is it possible to check through Charset class in Java or Kotlin?

Jabongg
  • 1,689
  • 2
  • 13
  • 28
Strangelove
  • 721
  • 6
  • 24
  • Possible duplicate of [Checking if a character is a special character in Java](https://stackoverflow.com/questions/12885821/checking-if-a-character-is-a-special-character-in-java) – Vishwa Ratna Jan 10 '19 at 12:05

2 Answers2

1

Unfortunately there is no dedicated function defined on Java's Charset to determine if it contains special characters.

Using a regular expression is completely fine but you could do it like this as well:

fun Char.isSpecialChar() = toLowerCase() !in 'a'..'z' && !isDigit() && !isWhitespace()

fun CharSequence.containsSpecialChars() = any(Char::isSpecialChar)

'H'.isSpecialChar() // false
'&'.isSpecialChar() // true
"Hello World".containsSpecialChars() // false
"Hello & Goodbye".containsSpecialChars() // true

This is a Kotlin solution, so if you have a Java Charset some casting might be necessary.

Willi Mentzel
  • 24,988
  • 16
  • 102
  • 110
0

Take a look at class java.lang.Character static member methods (isDigit, isLetter, isLowerCase, ...)

Example:

String str = "Hello World 123 !!";
int specials = 0, digits = 0, letters = 0, spaces = 0;
for (int i = 0; i < str.length(); ++i) {
   char ch = str.charAt(i);
   if (!Character.isDigit(ch) && !Character.isLetter(ch) && !Character.isSpace(ch)) {
      ++specials;
   } else if (Character.isDigit(ch)) {
      ++digits;
   } else if (Character.isSpace(ch)) {
      ++spaces;
   } else {
      ++letters;
   }
}

Reference:

Vishwa Ratna
  • 5,007
  • 5
  • 28
  • 49