Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to write string functions in Java?

How to write following string functions using Java?

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

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

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


1 Answer
Pythonista

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.