2

I'm given a String & I need to find whether it contains any special character or not? I tried using charAt() and ASCII values.But it didn't work.Someone please help.Thanks in advance.

for(int i=0;i<s.length();i++)
{
    char c=s.charAt(i);
    if(65<=c<=90)
    {
        System.out.println("Valid");
    }
    else if(97<=c<=122)
    {
        System.out.println("Invalid as it contains lower case letter");
        break;
    }
    else if(48<=c<=57)
    {
        System.out.println("Invalid as it contains numbers");
        break;
    }
    else
        System.out.println("Invalid as it contains special characters");
}
ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
Darpanjbora
  • 163
  • 3
  • 13
  • 3
    Which characters are the "special characters". Or to be more specific: Which characters are considered "OK"? – ParkerHalo Dec 29 '15 at 08:49
  • "it didn't work" doesn't tell us what your code looked like, or the input, or the expected output, or the actual output. Please provide a [mcve]. – Jon Skeet Dec 29 '15 at 08:49
  • Actually.. i want only the block letters. All others are considered as invalid. – Darpanjbora Dec 29 '15 at 08:51

4 Answers4

1

Something like this would work :

public static void main(String[] args) {
    String s = "asda®††∆˚∆asd121";
    System.out.println(s.replaceAll("[a-zA-Z0-9]", ""));
}

O/P :

®††∆˚∆

If the size after replacing is 0, then there were no special characters. You can update the regex with what you consider as special. :)

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
1

The problem you have is that something like this: 65<=c<=90 will not work in java. You can't chain compares!

You'll have to write something like this:

if (65 <= c && c <= 90)

Or to increase readability i'd suggest you to do something like this:

if ('A' <= c && c <= 'Z')
ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
  • OK. thats where the problem was. Thanks a lot. I didn't know that chain comparison is not possible in java. Thanks @parkerHalo. – Darpanjbora Dec 29 '15 at 09:01
1

In Java 65<=c<=90 is not a valid comparison.

You'll need to write your conditions like this:

if (65<=c && c<=90) {
    ...
} else if (97<=c && c<=122) {
    ...
}
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34
1

You can use StringUtils : isAllUpperCase

Or else try something like this in case you want to check for each character.

public static boolean isUpperCase(String s)
    {
        for (int i=0; i<s.length(); i++)
        {
            if (!Character.isUpperCase(s.charAt(i)))
            {
                return false;
            }
        }
        return true;

}
Rockstar
  • 2,228
  • 3
  • 20
  • 39