Write a Java Program to Remove Common Characters From Given Strings

Write a Java Program to Remove Common Characters From Given Strings thumbnail
43K
By Dhiraj Ray 10 March, 2018

Program Description

In many java interviews, it is asked this question to compare two strings and remove the common character from the given strings to check the programming aptitude.For example, suppose there are two string, s1 = "abcfgh" and s2 = "aasdf" and after removal of common character the value of s1 and s2 becomes bcgh and sd respectivly. Following is the java program to remove the common characters from any given strings.

CommonCharacter.java
package com.devglan.set1;

public class CommonCharacter {

    public void removeCommonCharacter(String s1, String s2){
        System.out.println("Before removing common character s1 " + s1);
        System.out.println("Before removing common character s2 " + s2);
        String commonChars = "";

        for (int i = 0; i < s1.length(); i++) {
            for (int j = 0; j < s2.length(); j++) {
                if (s1.charAt(i) == s2.charAt(j)) {
                    commonChars += s1.charAt(i);
                }
            }
        }

        for(int i = 0; i < commonChars.length(); i ++) {
            String charToRemove = commonChars.charAt(i)+"";
            s1 = s1.replace(charToRemove, "");
            s2 = s2.replace(charToRemove, "");
        }
        System.out.println("After removing common character " + s1);
        System.out.println("After removing common character " + s2);
    }

    public static void main(String[] args){
        CommonCharacter commonCharacter = new CommonCharacter();
        commonCharacter.removeCommonCharacter("abcfgh", "aasdf");
    }
}

Explanation

First use the nested loop and create a string with all the common characters and then replace common chars from the given strings with a blank.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.