How to write string functions in Java?


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;
}

Updated on: 30-Jul-2019

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements