如何检查字符串是否包含用户给定单词的字母

时间:2015-11-20 22:12:32

标签: java string letter contain

如何检查字符串是否包含用户的给定单词的字母,如

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;
    }
}

}

它在方法中不起作用。我试着5个小时请帮助我!!

我无法比较所有字母并将它们返回到主要方法

2 个答案:

答案 0 :(得分:1)

你太快回来了。顺便说一下,有更简洁的方法可以做到这一点,但我只是调整你的代码示例。

public static boolean occursIn(String pattern, String str){
    boolean allLettersFound = true;

    for(int i=0;pattern.charAt(i)<=str.length();i++){
        if(!str.contains(pattern.charAt(i))){
            allLettersFound = false;
            break;
        }
    }
    return allLettersFound;
}

答案 1 :(得分:0)

请检查以下代码(我已测试过):

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;
    }
}

输出:

s*h*l occurs in love hss