I am using Java 8. Suppose I have two Strings a=helloworld
and b=howareyou
respectively. I want to find out the matching characters of String b from String a along with their position in b. As in my example the matching characters are h
,e
,o
,w
,r
and r
is the 5th character in string b. I don't want to find if it is the substring or not. I just want to check if the characters of one string are present in another string or not. Is there any way to do that? Below is my Java Code.
public class CharCheck {
public static void main(String[] args) {
String a = "helloworld";
String b = "howareyou";
char st = containsAny(a, b);
System.out.println(st+", ");
}
private static char containsAny(String str1, String str2) {
if (str1 == null || str1.length() == 0 || str2 == null || str2.length() == 0) {
if (str1 == null || str1.length() == 0) {
return 'X';
}
}
for (int i = 0; i < str1.length(); i++) {
char ch = str1.charAt(i);
for (int j = 0; j < str2.length(); j++) {
if (str2.charAt(i) == ch) {
return ch;
}
}
}
return 'X';
}
}