在Java中如何使用函数来查找两个字符串中的公共单词?
发布时间:2023-07-04 06:31:08
要在Java中使用函数来查找两个字符串中的公共单词,可以遵循以下步骤:
1. 创建一个函数,用于查找两个字符串中的公共单词。函数可以接受两个参数,即两个字符串。
public List<String> findCommonWords(String str1, String str2) {
// 实现在这里
}
2. 在函数内部,首先将两个字符串分割成单词数组,可以使用Java的split方法。
String[] words1 = str1.split(" ");
String[] words2 = str2.split(" ");
3. 创建一个List对象,用于存储公共单词。
List<String> commonWords = new ArrayList<>();
4. 遍历一个单词数组,并检查每个单词是否在另一个单词数组中存在。如果存在,则将其添加到公共单词列表中。
for (String word : words1) {
if (Arrays.asList(words2).contains(word)) {
commonWords.add(word);
}
}
5. 返回包含公共单词的列表。
return commonWords;
综上所述,完整的Java函数代码如下所示:
public List<String> findCommonWords(String str1, String str2) {
String[] words1 = str1.split(" ");
String[] words2 = str2.split(" ");
List<String> commonWords = new ArrayList<>();
for (String word : words1) {
if (Arrays.asList(words2).contains(word)) {
commonWords.add(word);
}
}
return commonWords;
}
使用该函数可以轻松地找到两个字符串中的公共单词。例如:
String str1 = "Hello world"; String str2 = "Hello there"; List<String> commonWords = findCommonWords(str1, str2); System.out.println(commonWords);
输出结果应该为:
[Hello]
这是因为在给定的示例中,"Hello"是唯一在两个字符串中都存在的单词。
