Common Java String Coding Problems And Answers

This article consists of Commonly asked Java String coding problems and their solutions.

1) How do you reverse a String in Java using all possible ways?

We can reverse a string in many possible ways. The three most popular approaches are listed below.

a) By Using String Buffer

In Java, StringBuffer is a class representing a mutable sequence of characters. This is synchronized and thread-safe hence suitable for string modification.

public class ReverseString {

    public static void main(String[] args) {

        StringReverse("automationqahub");

    }
    public static void StringReverse(String str) {

        StringBuffer bf = new StringBuffer(str);
        System.out.println(bf.reverse());
        }
        }

b) Converting String to a character array.

In Java, a Character Array is a data structure used to store sequences of characters.

public class ReverseString {

    public static void main(String[] args) {

        StringReverse("automationqahub");

    }
    public static void StringReverse(String str) {
        char ar[] = str.toCharArray();
        for (int i = str.length() - 1; i >= 0; i--) {
            System.out.print(ar[i]);
        }}}

c) By Using Recursion

Recursion in Java is a technique that allows a function to call itself within the body of its own function.

public class ReverseString {

    public static void main(String[] args) {

        StringReverseusingRecursion("automationqahub");
    }
    public static void StringReverseusingRecursion(String str) {
        if ((str == null) || (str.length() <= 1))
            System.out.println(str);
        else {
            System.out.print(str.charAt(str.length() - 1));
            StringReverseusingRecursion(str.substring(0, str.length() - 1));
        }
        }
        }

2) Write a Java program to reverse words in a String by preserving spaces.

Input: hello world 
Output: olleh dlrow

Code:

class ReverseString {
    public static void main(String[] args) {
        String str = "hello world";
        
        String[] words = str.split(" ");
        String reversedString = "";
        
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            for (int j = word.length() - 1; j >= 0; j--) {
                reversedString += word.charAt(j);
            }
            reversedString += " ";
        }
        
        System.out.println(reversedString);
    }
}

3) Write a Java Program to check if String is Panagram or not.

Panagram String: A string is a Panagram String if it contains every letter of the alphabet at least once. Panagram strings must include every letter from A to Z and are usually case-insensitive.

Input: "The quick brown fox jumps over the lazy dog."
Output: The input string is a pangram 
import java.util.HashSet;

class PanagramChecking {
    public static void main(String[] args) {
        String input = "The quick brown fox jumps over the lazy dog";
        HashSet<Character> hs = new HashSet<Character>();

       for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
                hs.add(Character.toLowerCase(c)); // to avoid case-sensitivity issues
            }
        }

        System.out.println("Unique alphabetic characters: " + hs.size());
        if (hs.size() == 26) {
            System.out.println("The input string is a pangram.");
        } else {
            System.out.println("The input string is not a pangram.");
        }
    }
}

4) Write a Program in Java to find the longest common prefix among all Strings present in the array.

Input: arr[] =  {"avenge","avengers","avent","avb"};
Output: av

Code_1:

This code checks for each subsequent string if the current prefix is a prefix of the string. If not, reduce the prefix by one character, check again and continue until the current prefix is a prefix of all strings or it becomes empty.

public class LongestCommonPrefix {

    public static void main(String[] args) {
        String[] strs = {"avenge","avengers","avent","avb"};
        System.out.println(longestCommonPrefix(strs));  
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) return "";
        String prefix = strs[0];
        for (int i = 1; i < strs.length; i++) {
            while (strs[i].indexOf(prefix) != 0) {
                prefix = prefix.substring(0, prefix.length() - 1);
                if (prefix.isEmpty()) return "false";
            }
        }
        return prefix;
    }
}

Code_2:

The code below finds the longest common prefix by sorting the array of strings, comparing the first and last strings (which are the most different in a sorted array), and building the prefix character by character.

import java.util.Arrays;

public class LongestCommonPrefix {

  public static String longestCommonPrefix(String[] strs) {

    StringBuilder result = new StringBuilder();

    // Sort the array
    Arrays.sort(strs);

    // Get the first and last strings
    char[] first = strs[0].toCharArray();
    char[] last = strs[strs.length - 1].toCharArray();

    // Start comparing
    for (int i = 0; i < first.length; i++) {
      if (first[i] != last[i])
        break;
      result.append(first[i]);
    }

    return result.toString();
  }
   public static void main(String[] args) {
        String[] strs = {"avenge","avengers","avent","avb"};
        System.out.println(longestCommonPrefix(strs));  
    }

}

5) Given a list of words followed by two words, the task is to find the minimum distance between the given two words in the list of words.

Input: S = { "the", "quick", "brown", "fox", "quick"}
word1 = "the"
word2 = "fox"
Output: 3

Code:

class FindClosestString {
    public static void main(String[] args) {
      String arr[] = {"java", "for", "geeks", "contribute", "practice"};
       String word1="geeks";
       String word2 ="practice";
       int index1=0;
       int index2=0;
      
       for(int i=0;i<arr.length-1;i++)
       {
          
           if(arr[i]==word1)
           {
               index1 =i;
           }
           if(arr[i]==word2)
           {
               index2=i;
           }
           }
       System.out.println("distance is:"+Math.abs(index2-index1));
       }
}

6) Write a Java program to find if two Strings are Anagram or not.

Anagram String: Anagram strings are strings that can be transformed into each other by rearranging their characters. Example: “listen” and “silent” or “evil” and “vile”.

Code:

import java.util.Arrays;

public class AnagramCheck {

    public static boolean areAnagrams(String str1, String str2) {
        // Remove all white spaces and convert to lowercase
        str1 = str1.replaceAll("\\s", "").toLowerCase();
        str2 = str2.replaceAll("\\s", "").toLowerCase();

        
        if (str1.length() != str2.length()) {
            return false;
        }

        char[] charArray1 = str1.toCharArray();
        char[] charArray2 = str2.toCharArray();

        // Sort the char arrays
        Arrays.sort(charArray1);
        Arrays.sort(charArray2);

        return Arrays.equals(charArray1, charArray2);
    }

    public static void main(String[] args) {
        String str1 = "listen";
        String str2 = "silent";

        if (areAnagrams(str1, str2)) {
            System.out.println(str1 + " and " + str2 + " are anagrams.");
        } else {
            System.out.println(str1 + " and " + str2 + " are not anagrams.");
        }
    }
}

To read and solve more coding problems please visit this link.

Leave a Reply

Discover more from AutomationQaHub

Subscribe now to keep reading and get access to the full archive.

Continue reading