比较并从java中的2个数组中提取类似的字符串,不重复
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了比较并从java中的2个数组中提取类似的字符串,不重复,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1882字,纯文字阅读大概需要3分钟。
内容图文
![比较并从java中的2个数组中提取类似的字符串,不重复](/upload/InfoBanner/zyjiaocheng/726/499443c37ee04bdc8761f499d13d752b.jpg)
我试图从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()]);
}
内容总结
以上是互联网集市为您收集整理的比较并从java中的2个数组中提取类似的字符串,不重复全部内容,希望文章能够帮你解决比较并从java中的2个数组中提取类似的字符串,不重复所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。