Sharpen Your Skills: Programming Languages Practice Q&A

Programming practice questions

String in JAVA

 
1

Question- How to Print duplicate characters from String in JAVA Language?



Answer-
 Write a program to find repeated characters in a String. For example, if given input to your program is "Java", it     should print all duplicates characters, i.e. characters appear more than once in String and their count e.g. a = 2     because character 'a' has appeared twice in String "Java".

 The standard way to solve this problem is to get the character array from String, iterate through that and build a     Map with character and their count. Then iterate through that Map and print characters which have appeared         more than once. So you actually need two loops to do the job, the first loop to build the map and second loop to   print characters and counts.

 If you look at below example, there is only one static method called printDuplicateCharacters(), which does both   this job. We first got the character array from String by calling toCharArray().

 Next we are using HashMap to store characters and their count. We use containsKey() method to check if key,   which is a character already exists or not, if already exists we get the old count from HashMap by calling get()   method and store it back after incrementing it by 1.

 import java.util.HashMap;
 import java.util.Map;
 import java.util.Scanner;
 import java.util.Set;

 /* Java Program to find duplicate characters in String.
   @author CSDT
  */
   public class FindDuplicateCharacters
    {
        public static void main(String args[])
               {
                    printDuplicateCharacters("Programming");
                   printDuplicateCharacters("Combination");
                   printDuplicateCharacters("Java");
              }

    /*
     * Find all duplicate characters in a String and print each of them.
     */
    public static void printDuplicateCharacters(String word)
           {
               char[] characters = word.toCharArray();

        // build HashMap with character and number of times they appear in String
        Map<Character, Integer> charMap = new HashMap<Character, Integer>();
        for (Character ch : characters)
          {
            if (charMap.containsKey(ch))
         {
                charMap.put(ch, charMap.get(ch) + 1);
            }
        else
         {
                charMap.put(ch, 1);
            }
        }
        // Iterate through HashMap to print all duplicate characters of String
        Set<Map.Entry<Character, Integer>> entrySet = charMap.entrySet();
        System.out.printf("List of duplicate characters in String '%s' %n", word);
        for (Map.Entry<Character, Integer> entry : entrySet)
                  {
            if (entry.getValue() > 1)
             {
                System.out.printf("%s : %d %n", entry.getKey(), entry.getValue());
                  }
             }
        }

    }
2

Question- How to check if two Strings are anagrams of each other in Java Language?



Answer-
How to check if two Strings are anagrams of each other?

A simple coding problem based upon String, but could also be asked with numbers. You need to write a Java program to check if two given strings are anagrams of Each other. Two strings are anagrams if they are written using the same exact letters, ignoring space, punctuation, and capitalization. Each letter should have the same count in both strings. For example, the Army and Mary are an anagram of each other.

    import java.util.Arrays;
   /**
  * Java program - String Anagram Example.
  * This program checks if two Strings are anagrams or not
  *
 * @author CSDT Patna
 */
   public class AnagramCheck {
   
    /*
     * One way to find if two Strings are anagram in Java. This method
     * assumes both arguments are not null and in lowercase.
     *
     * @return true, if both String are anagram
     */
    public static boolean isAnagram(String word, String anagram){       
        if(word.length() != anagram.length()){
            return false;
        }
       
        char[] chars = word.toCharArray();
       
        for(char c : chars){
            int index = anagram.indexOf(c);
            if(index != -1){
                anagram = anagram.substring(0,index) + anagram.substring(index +1, anagram.length());
            }else{
                return false;
            }           
        }
       
        return anagram.isEmpty();
    }
   
    /*
     * Another way to check if two Strings are anagram or not in Java
     * This method assumes that both word and anagram are not null and lowercase
     * @return true, if both Strings are anagram.
     */
    public static boolean iAnagram(String word, String anagram){
        char[] charFromWord = word.toCharArray();
        char[] charFromAnagram = anagram.toCharArray();       
        Arrays.sort(charFromWord);
        Arrays.sort(charFromAnagram);
       
        return Arrays.equals(charFromWord, charFromAnagram);
    }
   
   
    public static boolean checkAnagram(String first, String second){
        char[] characters = first.toCharArray();
        StringBuilder sbSecond = new StringBuilder(second);
       
        for(char ch : characters){
            int index = sbSecond.indexOf("" + ch);
            if(index != -1){
                sbSecond.deleteCharAt(index);
            }else{
                return false;
            }
        }
       
        return sbSecond.length()==0 ? true : false;
    }
 }