java中修改和删除的单词,如何在Java中从String中消除重复的单词?

I have an ArrayList of Strings and it contains records such as:

this is a first sentence

hello my name is Chris

what's up man what's up man

today is tuesday

I need to clear this list, so that the output does not contain repeated content. In the case above, the output should be:

this is a first sentence

hello my name is Chris

what's up man

today is tuesday

as you can see, the 3rd String has been modified and now contains only one statement what's up man instead of two of them.

In my list there is a situation that sometimes the String is correct, and sometimes it is doubled as shown above.

I want to get rid of it, so I thought about iterating through this list:

for (String s: myList) {

but I cannot find a way of eliminating duplicates, especially since the length of each string is not determined, and by that I mean there might be record:

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

or sometimes short ones:

single word singe word

is there some native java function for that maybe?

解决方案

I would suggest using regular expressions. I was able to remove duplicates using this pattern: \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);

}

}

}

}

Results:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值