使用Java编写一个函数来查找一个字符串中是否包含某个关键字
发布时间:2023-07-02 14:41:16
这里提供两种方法来实现在一个字符串中查找某个关键字的功能。
方法一:使用indexOf函数
public boolean containsKeyword(String str, String keyword) {
if (str == null || keyword == null) {
return false;
}
return str.indexOf(keyword) != -1;
}
这个函数使用了String类的indexOf函数来查找关键字在字符串中的位置。如果关键字在字符串中找到,indexOf函数会返回关键字的起始位置,否则返回-1。根据返回值是否为-1来判断关键字是否存在。
方法二:使用正则表达式
import java.util.regex.*;
public boolean containsKeyword(String str, String keyword) {
if (str == null || keyword == null) {
return false;
}
String regex = "\\b" + keyword + "\\b"; // 使用\b来匹配关键字的边界
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
return matcher.find(); // 返回是否找到匹配的关键字
}
这个函数使用了Pattern和Matcher类来实现正则表达式的匹配。通过构建正则表达式 "\\b" + keyword + "\\b" ,我们可以匹配关键字的边界,以避免匹配到部分关键字。
需要注意的是,在方法二中,我们需要导入java.util.regex.*包。
下面是两个函数的示例用法:
public static void main(String[] args) {
String str = "This is a test string.";
String keyword = "test";
System.out.println(containsKeyword(str, keyword)); // 输出 true
keyword = "foo";
System.out.println(containsKeyword(str, keyword)); // 输出 false
}
这样就可以使用Java编写一个函数来判断一个字符串中是否包含某个关键字了。
