How to write string functions in Java?

Java 8Object Oriented ProgrammingProgramming

1) take a string from the user and check contains atleast one digit or not:

Extract character array from string using toCharArray() method. Run a for loop over each character in array and test if it is a digit by static method isDigit() of character class

public static boolean chkdigit(String str) {
   char arr[]=str.toCharArray();
   for (char ch:arr) {
      if (Character.isDigit(ch)) {
         return true;
      }
   }
   return false;
}

2.) take a string from the user and check contains atleast one alphabets or not

Similarly isLetter() method of character class is used to check if character in string is an alphabet

public static boolean chkalpha(String str) {
   char arr[]=str.toCharArray();
   for (char ch:arr) {
      if (Character.isLetter(ch)) {
         return true;
      }      
   }
   return false;
}

 3). take a string from the user and check contains atleast one chars or not

Simply find the length of string and check if it is 0

public static boolean chklen(String str) {
   if (str.length()==0)
      return true;
   else
      return false;
}
raja
Published on 01-May-2018 15:10:00
Advertisements