Search code examples
javastringlettercontain

How can i check a string whether it contains letters of a given word by user


how can i check a string whether it contains letters of a given word by user like

Enter the pattern string: shl

Enter a string: school

shl occurs in ”school”

Enter a string: okul

shl does NOT occur in ”okul”

Enter a string: salaries are neither high nor low

shl occurs in ”salaries are neither high nor low”

Enter a string: This is a good school, isn’t it? 

shl occurs in ”This is a good school, isn’t it?”

Enter a string: I love programming 

shl does NOT occur in ”I love programming”





if (occursIn(pattern,str)){

                System.out.println(pattern + " occurs in " + str);
            }
            else{
                System.out.println(pattern + " does not occurs in " + str);
            }

public static boolean occursIn(String pattern, String str){

for(int i=0;pattern.charAt(i)<=str.length();i++){

        if(str.contains(pattern.charAt(i))){
            return true;
    }
        else {
            return false;
    }
}

}

it doesnt work in a method. Im trying for 5 hours please help me !!

i cant compare all of the letters and return them to the main method


Solution

  • Please check the following code (I have tested it):

    public class OccursIn {
        public static void main(String[] args) {
            String pattern = "s*h*l";
            String str = "love hss";
            if (occursIn(pattern, str)) {
                System.out.println(pattern + " occurs in " + str);
            } else {
                System.out.println(pattern + " does not occurs in " + str);
            }
        }
    
        public static boolean occursIn(String pattern, String str) {
            for (int i = 0; i < pattern.length(); i++) {
                String c = pattern.substring(i, i + 1);
                if (!"*".equalsIgnoreCase(c) && !str.contains(c)) {
                    return false;
                }
            }
            return true;
        }
    }
    

    Output:

    s*h*l occurs in love hss