How do we find out if first character of a string is a number in java?


Using the isDigit() method

The isDigit() method of the java.lang.Character class accepts a character as a parameter and determines whether it is a digit or not. If the given character is a digit this method returns true else, this method returns false.

Therefore, to determine whether the first character of the given String is a digit.

  • The charAt() method of the String class accepts an integer value representing the index and returns the character at the specified index. 

  • The toCharArray() method of this class converts the String to a character array and returns it you can get its first character as array[0].

  • Retrieve the 1st character of the desired String using either of the methods.

  • Then, determine whether it is a digit or not by passing it as a parameter to the isDigit() method.

Example

import java.util.Scanner;
public class FirstCharacterOfString {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String str = sc.next();
      //Converting String to a character array
      char charArray[] = str.toCharArray();
      boolean bool = Character.isDigit(charArray[0]);
      if(bool) {
         System.out.println("First character is a digit");
      } else {
         System.out.println("First character is not a digit");
      }
   }
}

Output1

Enter a String
krishna
First character is not a digit

Output2

Enter a String
2sample
First character is a digit

Using the regular expressions.

The matches() method of the String class accepts a regular expression and verifies it matches with the current String, if so, it returns true else, it returns false.

The regular expression to match String which contains a digit as first character is “^[0-9].*$”. Pass this as a parameter to the matches() method of the String class.

Example

import java.util.Scanner;
public class FirstCharacterOfString {
   public static void main(String args[]) {
      //reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String str = sc.next();
      boolean bool = str.matches("^[0-9].*$");
      if(bool) {
         System.out.println("First character is a digit");
      } else {
         System.out.println("First character is not a digit");
      }
   }
}

Output1

Enter a String
krishna
First character is not a digit

Output2

Enter a String
2sample
First character is a digit
raja
Published on 10-Oct-2019 11:06:47
Advertisements