READ SPECIAL CHARACTER IN JAVA STRINGS

Jeet Verma

Total Post:110

Points:776
Posted by  Jeet Verma
Java  String 
 636  View(s)
Ratings:
Rate this:
I want to test wheather my input string conatins any special characters or not. Is there any good techniques for impelmting this?

I am using charAt() and ASCII values
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");
}
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Read Special Character in java Strings

    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')

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!