在Java中如何消除字符串中的重复单词?

3

我有一个包含StringArrayList,其中包含如下记录:

this is a first sentence
hello my name is Chris 
what's up man what's up man
today is tuesday

我需要清空这个列表,以便输出内容不包含重复的内容。在上面的情况下,输出应该是:
this is a first sentence
hello my name is Chris 
what's up man
today is tuesday

正如您所见,第三个字符串已被修改,现在只包含一个语句what's up man而不是两个。

在我的列表中,有时字符串是正确的,有时它会像上面显示的那样重复。

我想摆脱它,所以我考虑遍历这个列表:

for (String s: myList) {

但我找不到消除重复项的方法,尤其是由于每个字符串的长度未确定,也就是说可能会有记录:

this is a very long sentence this is a very long sentence

有时候会有短的版本:
single word singe word

有没有一些原生的Java函数可以做到这一点呢?

2
你可以使用 line.split(" ") 将每一行拆分成字符串数组,然后将它们添加到 LinkedHashSet 中,最后再读取出来。 - 4castle
不是一个函数,但你可以实现这个逻辑:通过分隔符<空格>将每个单词拆分,并将其添加到集合中... 然后检索回来。 - minigeek
@4castle 哈哈..并发评论 - minigeek
@user3766930,我添加了我的解决方案。让我知道吧 ;) 我已经测试成功了。 - minigeek
查看此示例代码。希望这对您有用! - Fakhar
显示剩余2条评论
6个回答

2
假设字符串重复两次,并且在中间有一个空格,像你的示例一样,以下代码将删除重复内容:
for (int i=0; i<myList.size(); i++) {
    String s = myList.get(i);
    String fs = s.substring(0, s.length()/2);
    String ls = s.substring(s.length()/2+1, s.length());
    if (fs.equals(ls)) {
        myList.set(i, fs);
    }
}

这段代码将列表中的每个条目分成两个子字符串(通过中点分割)。如果两者相等,则用一个半部分替换原始元素,从而消除重复。

我正在测试代码,没有看到@Brendan Robert的答案。此代码遵循与他答案相同的逻辑。


2
我建议使用正则表达式。我能够使用以下模式删除重复项:\b([\w\s']+) \1\b
public class Main {
    static String [] phrases = {
            "this is a first sentence",
            "hello my name is Chris",
            "what's up man what's up man",
            "today is tuesday",
            "this is a very long sentence this is a very long sentence",
            "single word single word",
            "hey hey"
    };
    public static void main(String[] args) throws Exception {
        String duplicatePattern = "\\b([\\w\\s']+) \\1\\b";
        Pattern p = Pattern.compile(duplicatePattern);
        for (String phrase : phrases) {
            Matcher m = p.matcher(phrase);
            if (m.matches()) {
                System.out.println(m.group(1));
            } else {
                System.out.println(phrase);
            }
        }
    }
}

结果:

this is a first sentence
hello my name is Chris
what's up man
today is tuesday
this is a very long sentence
single word
hey

1

//在Java 8中实现

String str1 = "I am am am a good Good coder";
        String[] arrStr = str1.split(" ");
        String[] element = new String[1];
        return Arrays.stream(arrStr).filter(str1 -> {
            if (!str1.equalsIgnoreCase(element[0])) {
                element[0] = str1;
               return true;
            }return false;
        }).collect(Collectors.joining(" "));

1

假设:

  1. 大写单词等同于小写单词。

String fullString = "lol lol";
String[] words = fullString.split("\\W+");
StringBuilder stringBuilder = new StringBuilder();
Set<String> wordsHashSet = new HashSet<>();

for (String word : words) {
    // Check for duplicates
    if (wordsHashSet.contains(word.toLowerCase())) continue;

    wordsHashSet.add(word.toLowerCase());
    stringBuilder.append(word).append(" ");
}
String nonDuplicateString = stringBuilder.toString().trim();

你需要一个转换为小写的函数,假设单词在大小写不同时是相同的。 - HopefullyHelpful
增加了假设。 - Veneet Reddy

1
简单逻辑:按标记空格(" ")分割每个单词,然后将其添加到LinkedHashSet中,再检索回来,替换“[”,“]”,“,”。
 String s = "I want to walk my dog I want to walk my dog";
 Set<String> temp = new LinkedHashSet<>();
 String[] arr = s.split(" ");

 for ( String ss : arr)
      temp.add(ss);

 String newl = temp.toString()
          .replace("[","")
          .replace("]","")
          .replace(",","");

 System.out.println(newl);

输出:我想遛狗


0

这取决于您的情况,但假设字符串最多可以重复两次而不是三次或更多次,您可以找到整个字符串的长度,找到中间点,并将中间点后的每个索引与匹配的起始索引进行比较。如果字符串可以重复多次,则需要更复杂的算法,首先确定字符串重复的次数,然后找到每个重复的起始索引,并截断从第一个重复开始的所有索引。如果您可以提供一些有关您希望处理的可能情况的上下文,我们可以开始组合一些想法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接