Find the uncommon values concatenated from both the strings in Java

JavaServer Side ProgrammingProgramming

To find the uncommon values concatenated from both the strings in Java, the code is as follows −

Example

 Live Demo

import java.util.*;
import java.lang.*;
import java.io.*;
public class Demo{
   public static String concat_str(String str_1, String str_2){
      String result = "";
      int i;
      HashMap<Character, Integer> my_map = new HashMap<Character, Integer>();
      for (i = 0; i < str_2.length(); i++)
      my_map.put(str_2.charAt(i), 1);
      for (i = 0; i < str_1.length(); i++)
      if (!my_map.containsKey(str_1.charAt(i)))
      result += str_1.charAt(i);
      else
      my_map.put(str_1.charAt(i), 2);
      for (i = 0; i < str_2.length(); i++)
      if (my_map.get(str_2.charAt(i)) == 1)
      result += str_2.charAt(i);
      return result;
   }
   public static void main(String[] args){
      String my_str_1 = "ABMCD";
      String my_str_2 = "MNCPQR";
      System.out.println("The uncommon values concatenated from both strings is : ");
      System.out.println(concat_str(my_str_1, my_str_2));
   }
}

Output

The uncommon values concatenated from both strings is :
ABDNPQR

A class named Demo contains a function anmed ‘concat_str’ which takes in two strings as parameters. The function creates a new HashMap instance, and iterates over the map, and places elements into it for both the strings.

The two strings are compared by iterating over them, and if the characters are same, then the iterator just increments, otherwise, both the elements are put into another string named ‘result’. This string is returned as output. In the main function, two strings are defined and the ‘concat_str’ function is called on these two strings. The output is displayed on the console.

raja
Published on 08-Jul-2020 10:15:16
Advertisements