Pages

Remove common characters from given strings

Remove common characters from given strings

  • We can remove common characters from given strings using for loops and string replace method.
Example:

1) s1 = abc@ , s2 = cd@e
Modified s1 = ab,  Modified s2 = de

If you notice above example  ‘c’ and ‘@’ were common characters and both have been deleted from both strings.

2) s1 = abc@c , s2 = cd@ee Modified s1 = abc, Modified s2 = dee If you notice above example ‘@’ and ‘c’ were common characters and both have been deleted from both strings.

Program:
public class commonCharacters {
public static void main(String[] args) {
String s1 = "abc@c";
String s11 = s1;
String s2 = "cd@ee";
String s22 = s2;


for (int i = 0; i <= s1.length() - 1; i++) {
if (s2.contains((String.valueOf(s1.charAt(i))))) {
s22 = s22.replaceFirst(String.valueOf(s1.charAt(i)), "");
}
}
System.out.println("removed common characters in string " + s2 + " is =" + s22);


for (int i = 0; i <= s2.length() - 1; i++) {
if (s1.contains((String.valueOf(s2.charAt(i))))) {
s11 = s11.replaceFirst(String.valueOf(s2.charAt(i)), "");
}
}
System.out.println("removed common characters in string " + s1 + " is =" + s11);

System.out.println("After concat-Remove Common characters in two strings = " + s11 + s22);
}
}
Output:
Remove common characters from given strings
Remove common characters from given strings

Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.