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?
Asked
Active
Viewed 260 times
0

Jabongg
- 2,099
- 2
- 15
- 32

Strangelove
- 761
- 1
- 7
- 29
-
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 Answers
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
- 27,862
- 20
- 113
- 121
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;
}
}

Vishwa Ratna
- 5,567
- 5
- 33
- 55