Java code to print common characters of two Strings in alphabetical order

JavaServer Side ProgrammingProgramming

To print common characters of two strings in alphabetical order, the code is as follows −

Example

 Live Demo

import java.io.*;
import java.util.*;
public class Demo{
   static void common_chars(String str_1, String str_2){
      int[] array_1 = new int[26];
      int[] array_2 = new int[26];
      int str_len_1 = str_1.length();
      int str_len_2 = str_2.length();
      for (int i = 0 ; i < str_len_1 ; i++)
      array_1[str_1.charAt(i) - 'a'] += 1;
      for (int i = 0 ; i < str_len_2 ; i++)
      array_2[str_2.charAt(i) - 'a'] += 1;
      for (int i = 0 ; i < 26 ; i++){
         if (array_1[i] != 0 && array_2[i] != 0){
            for (int j = 0 ; j < Math.min(array_1[i], array_2[i]) ; j++)
            System.out.print(((char)(i + 'a')));
         }
      }
   }
   public static void main(String[] args) throws IOException{
      String my_str_1 = "itsasample";
      String my_str_2 = "thisisasample";
      System.out.println("The common characters between the two strings in alphabetical order is :
   ");
      common_chars(my_str_1, my_str_2);
   }
}

Output

The common characters between the two strings in alphabetical order is :
aaeilmpsst

A class named Demo contains a function named ‘common_chars’, that declares two integer arrays of size 26 (indicating the 26 alphabets in English). Their lengths are stored in two different variables respectively.

The arrays are iterated over and at the index of different between ascii of ‘a’ and ascii of every character, ascii of the character ‘a’ is subtracted from every character’s ascii value and incremented by 1. This will fill up only those values in the array that are common. The minimum number of characters from both the arrays is computed and printed on the console. In the main function, the two strings are defined and the function is called by passing these two strings as parameters.

raja
Published on 08-Jul-2020 10:20:21
Advertisements