Java Puzzle – Check if a String contains All Alphabets

1. What is a Complete String?

A string is said to be complete if it contains all the characters from a to z. If it misses even a single character, it is considered an incomplete string.

For example, the following string is a complete string. It contains all the characters from the alphabet.

qwertyuioplkjhgfdsazxcvbnm

2. Java Program using For-Loop

In the following Java program, we perform two checks:

  • If the string length is less than 26, there is definitely a missing character(s).
  • In a for-loop, we check each character in the string (case-insensitive), and even if a single character is missing, we return false.
public static boolean checkAllAlphabets(String input) {

  //If input length is less than 26 then it can never be complete
  if (input.length() < 26) {
    return false;
  }

  //Even a single character is missing, return false
  for (char ch = 'A'; ch <= 'Z'; ch++) {
    if (input.indexOf(ch) < 0 && input.indexOf((char) (ch + 32)) < 0) {
      return false;
    }
  }
  return true;
}

3. Java Program using Regex

The following Java program uses regular expression. The regex checks that each of the 26 characters must occur at least once in the input string.

public static boolean checkAllCharsUsingRegex(String input) {

  //If input length is less than 26 then it can never be complete
  if (input.length() < 26) {
    return false;
  }
  //Even a single character is missing, return false
  String regex = "(?i)(?=.*a)(?=.*b)(?=.*c)(?=.*d)(?=.*e)(?=.*f)"
      + "(?=.*g)(?=.*h)(?=.*i)(?=.*j)(?=.*k)(?=.*l)(?=.*m)(?=.*n)"
      + "(?=.*o)(?=.*p)(?=.*q)(?=.*r)(?=.*s)(?=.*t)(?=.*u)(?=.*v)"
      + "(?=.*w)(?=.*x)(?=.*y)(?=.*z).*";

  if (input.matches(regex)) {
    return true;
  }
  return false;
}

Happy Learning !!

Comments

Subscribe
Notify of
guest
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode