Get common characters in given two strings
- In given two strings, find common characters between two strings.
Examples:
Input:
String s1="xyabf";
String s2="xzcfa";
o/p: xaf xfa
Here, characters xaf are common in both string1 and string2
Input:
String s1="ramu";
String s2="somu";
o/p: mu mu
Program:
public class removeUnCommonCharacters {
public static void main(String[] args) {
// get common characters
String s1 = "xyabf";
String s2 = "xzcfa";
String unCommonS1 = "";
for (int i = 0; i <= s1.length() - 1; i++) {
if (s2.contains((String.valueOf(s1.charAt(i))))) {
unCommonS1 += s1.charAt(i);
}
}
System.out.println("Common characters in string " + s1 + " is = " + unCommonS1);
String unCommonS2 = "";
for (int i = 0; i <= s2.length() - 1; i++) {
if (s1.contains((String.valueOf(s2.charAt(i))))) {
unCommonS2 += s2.charAt(i);
}
}
System.out.println("Common characters in string " + s2 + " is = " + unCommonS2);
System.out.println("concat-common characters in strings " + s1 + "," + s2 + " is = " + (unCommonS1 + " " + unCommonS2));
}
}
Output:
Get common characters in given two strings |
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.