You are here : Home / Core Java Tutorials / Interview Programs (beginner to advanced) in java / Level1 programs for (beginner)
In this core java programming tutorial we will Write a program to delete repeated characters from two strings in java.
Take two Strings, compare them and delete repeated characters from two strings, when a match is found in the other string.
Example 1 in java>
s1 = abc , s2 = cde
Modified s1 = ab, Modified s2 = de
If you notice above example ‘c’ was common character and has been deleted from both strings.
Example 2 in java>
s1 = abc@ , s2 = cd@e
Modified s1 = ab, Modified s2 = de
If you notice above example ‘c’ and ‘@’ were common characters and both has been deleted from both strings.
Example 3 in java>
s1 = aBc , s2 = bcde
Modified s1 = a, Modified s2 = de
If you notice above example ‘b’ and ‘c’ were common characters and both has been deleted from both strings. We don’t care about case sensitivity.
Program/ example to delete repeated characters from two strings in java >
public class DeleteRepetaedCharacterFromBothStringsExample {
public static void main(String[] args) {
String s1 = "aBc";
String s2 = "bcde";
System.out.println("s1 = " + s1 + " , s2 = " + s2);
char ar1[] = s1.toCharArray();
char ar2[] = s2.toCharArray();
for (int i = 0; i < ar1.length; i++) {
boolean bMatch = false;
for (int j = 0; j < ar2.length; j++) {
if ((String.valueOf(ar1[i])).toLowerCase().equals(
((String.valueOf(ar2[j])).toLowerCase()))) {
bMatch = true;
break;
}
}
if (bMatch) {
s1 = s1.replaceAll(String.valueOf(ar1[i]).toUpperCase(), "");
s1 = s1.replaceAll(String.valueOf(ar1[i]).toLowerCase(), "");
s2 = s2.replaceAll(String.valueOf(ar1[i]).toLowerCase(), "");
s2 = s2.replaceAll(String.valueOf(ar1[i]).toUpperCase(), "");
}
}
System.out.println("Modified s1 = " + s1 + ", Modified s2 = " + s2);
}
}
/*output
s1 = abc , s2 = cde
Modified s1 = ab, Modified s2 = de
*/
|
So in this core java programming tutorial we Wrote a program to delete repeated characters from two strings in java.
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.
Related >
Labels:
Core Java
Level1 programs (beginners)