0

I have a string (length 3-8) assigned to a variable (text). I want to check whether the 2nd and 3rd characters are NOT numeric (a letter or symbol or space..or anything other than numbers).

AUJ
  • 73
  • 1
  • 1
  • 4

3 Answers3

0

Elementary way to do this could be:

if(((text.charAt(1)-'0')>=0)&&(text.charAt(1)-'0')<10))||((text.charAt(2)-'0')>=0)&&(text.charAt(2)-'0')<10)))
{
   //do nothing, since this means 2nd and/or 3rd characters in the string are numeric
}
else
{
                // Your condition is met
}

You could also use REGEX's , if your checking is still more complicated.

SoulRayder
  • 5,072
  • 6
  • 47
  • 93
0

Here is Another way to achieve this:

    boolean isNumeric = true;
    String test = "testing";
    char second = test.charAt(1);
    char third = test.charAt(2);

    try {
        Integer.parseInt(String.valueOf(second));
        Integer.parseInt(String.valueOf(third));
    } catch(NumberFormatException e) {
        isNumeric = false;
    }
    System.out.println("Contains Number in 2nd and 3rd or both position: " + isNumeric);
Peshal
  • 1,508
  • 1
  • 12
  • 22
0

You might make use of the String.IndexOf(String) method, like:

    String digits = "0123456789";
String s2 = text.substring(2,3);
String s3 = text.substring(3,4);
boolean valid = (digits.indexOf(s2) > -1) && (digits.indexOf(s3) > -1);
ErstwhileIII
  • 4,829
  • 2
  • 23
  • 37