43K
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.