-5

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';
   }
}
WASEEM
  • 187
  • 3
  • 14

1 Answers1

1

Im not going to implement the solution for you but I'll give you the pusedocode.

for each letter1 in String1 
     for each letter2 in String2 
          if letter1 is letter2 then print its position 

So you know you will need a nested for loop and a comparison, it becomes a bit more complicated if you want unique duplicates but i'll leave the rest up to you

Mitch
  • 3,342
  • 2
  • 21
  • 31