gpt4 book ai didi

java - 比较并从java中的2个数组中提取相似的字符串,不重复

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:08:33 25 4
gpt4 key购买 nike

我正在尝试从 2 个数组中提取相似的字符串,并且我已经成功地做到了,只是它们在重复。即 array 1 {"arrow", "arrow", "sycophant"}array 2 ("arrow", "sycophant", "bulbasaur"} 会给我{"arrow", "arrow","sycophant"} 的输出,而我只想获得一次箭头。有什么建议吗?

public static void main(String[] args) {
String[] words1 = { "sycophant", "rattle", "zinc", "alloy", "tunnel", "arrow" };
String[] words2 = { "sycophant", "arrow", "arrow" };

// String prefix = "a";
// String substring = "at";
// char[] letters = { 'a', 'b' };

// String[] output = wordsStartingWith(words1, prefix);
// String[] output = wordsContainingPhrase(words1, substring);
// String[] output = wordsContainingAll(words1, letters);
String[] output = wordsInBoth(words1, words2);

for (int i = 0; i < output.length; i++) {
System.out.println("Words: " + i + " " + output[i]);
}
}

public static String[] wordsInBoth(String[] words1, String[] words2) {
// method that finds and returns common words in two arrays
String[] returnWords;
int countWords = 0;

for (int i = 0; i < words1.length; i++) {
for (int j = 0; j < words2.length; j++) {
if (words1[i].equalsIgnoreCase(words2[j])) {
countWords++;
}
}
}

returnWords = new String[countWords];
countWords = 0;

for (int i = 0; i < words1.length; i++) {
for (int j = 0; j < words2.length; j++) {
if (words1[i].equalsIgnoreCase(words2[j])
&& !words1[i].equalsIgnoreCase(returnWords[countWords])) {
returnWords[countWords] = words1[i];
countWords++;
}
}
}

return returnWords;
}

最佳答案

一种可能性是存储在 HashSet 中找到的单词,这不会添加重复项。

// method that finds and returns common words in two arrays
public static String[] wordsInBoth(String[] words1, String[] words2) {

Set<String> returnWords = new HashSet<String>();

for (int i = 0; i < words1.length; i++) {
for (int j = 0; j < words2.length; j++) {
if (words1[i].equalsIgnoreCase(words2[j]))
returnWords.add(words1[i]);
}
}

return returnWords.toArray(new String[returnWords.size()]);
}

关于java - 比较并从java中的2个数组中提取相似的字符串,不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35190047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com