在java中:如何知道一个单词是否存在于长字符串中?

在java中:如何知道一个单词是否存在于长字符串中?,java,arrays,string,Java,Arrays,String,请告诉我是否有办法检查长字符串中是否存在字符串? 示例:检查此字符串abcdffgfghdshghhelloasdf中是否存在单词hello 在这种情况下,应该返回true 致以最良好的祝愿, Maya只需使用contains方法即可完成此操作 在Java中,您可以通过多种方式实现这一点,例如使用String类中的方法: 包含方法-将CharSequence作为参数: boolean checkContains(){ String orig="abcdffgfghdshghelloasd

请告诉我是否有办法检查长字符串中是否存在字符串? 示例:检查此字符串abcdffgfghdshghhelloasdf中是否存在单词hello 在这种情况下,应该返回true

致以最良好的祝愿,
Maya

只需使用contains方法即可完成此操作


在Java中,您可以通过多种方式实现这一点,例如使用String类中的方法: 包含方法-将CharSequence作为参数:

boolean checkContains(){
    String orig="abcdffgfghdshghelloasdf";
    return orig.contains("hello");
}
boolean checkMatches(){
    String orig="abcdffgfghdshghelloasdf";
    return orig.matches(".*hello.*");
}
匹配方法-作为参数:

boolean checkContains(){
    String orig="abcdffgfghdshghelloasdf";
    return orig.contains("hello");
}
boolean checkMatches(){
    String orig="abcdffgfghdshghelloasdf";
    return orig.matches(".*hello.*");
}

这两种方法都非常快,因此您将使用哪种方法没有太大区别。

根据上下文,使用toLowerCase或toUpperCase之类的方法可能也很有用。为什么不直接返回orig.containshello呢?还要注意的是,问号had hello都是小写的,并且预期结果为true,而您的代码返回false,因为mixedcase hello不在string.FFS中!请不要使用if-exp-true-else-false反模式。首先,它让我感到偏头痛。它们都比园艺快,但第一种方法比第二种方法快几个数量级,而且不容易出错。非常感谢你,我不知道。