需要一种更好的方法来查找字符串中的重复单词
我需要一种用更少的代码来完成相同操作的方法。这将帮助我更好地理解 Java。以下代码的输出将是:new, boy, 3pm, to
public class substring {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str= "a new, boy with new haircut boy, 3pm to boy 8pm margian 3pm to ghost";
String concant = "";
int occurance =0;
str = str.replaceAll(",", "");
System.out.println(str);
String[] subStr = str.split("s");
for(String sub:subStr)
{
for (String sub1:subStr) {
if(sub.equals(sub1))
{
occurance++;
if(occurance>=2)
{
if(!concant.contains(sub))
{
if(concant!= "")
concant = concant +", "+ sub;
else
concant = sub;
}
}
}
}
occurance = 0;
}
System.out.println(concant);
}
}
回答
解决方案
您可以利用集合数据结构提供的功能,而不是使用嵌套循环。集合是不能包含重复项的集合。因此,通过检查 add 方法的真实性,您可以确定重复项
String[] listContainingDuplicates = "a new, boy with new haircut boy, 3pm to boy 8pm margian 3pm to ghost".split("[,s]+");
final LinkedHashSet<String> duplicates = new LinkedHashSet<String>();
final Set<String> temp = new HashSet<>();
for (String current : listContainingDuplicates){
if (!temp.add(current))
duplicates.add(current);
}
System.out.println(duplicates.toString());
将此视为伪代码。可能存在您想要处理的边缘情况
- @NikolaiDmitriev It doesn't miss the point. The question asks for a better method. And this is it (once the string is correctly split).