我试图从2个数组中提取类似的字符串,我设法这样做,除了它们是重复的.即数组1 {“箭头”,“箭头”,“sycophant”}和数组2(“箭头”,“sycophant”,“bulbasaur”}将给我输出{“箭头”,“箭头”,“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()]);
}