【问题标题】:Remove duplicate set of strings in a hyphen separated big string删除连字符分隔的大字符串中的重复字符串集
【发布时间】:2020-06-15 15:34:47
【问题描述】:

我正在使用 Java 进行开发,我有以下字符串:

String duplicates = "Smith, John - Smith, John - Smith, John – Wilson, Peter";

我需要得到一个没有重复名称的新字符串。

unique = "Smith, John – Wilson, Peter";

我认为我可以使用

String unique[] = duplicates.split("-");

用逗号分隔连字符的问题是现在我有所有逗号

Smith, John, Smith, John, Smith, John, Wilson, Peter

任何帮助将不胜感激

【问题讨论】:

  • 我认为你需要用逗号而不是破折号分割?
  • 是的,我知道你的意思,但是有没有办法使用连字符?
  • 这些名字不是完整的“史密斯,约翰”吗?在这种情况下,您可以通过 split('-') 获得正确的名称?
  • 例如,以下将打印唯一名称:String str = "Smith, John - Smith, John - Smith, John - Wilson, Peter";Arrays.stream(str.split("-")).map(s->s.trim()).distinct().forEach(System.out::println);

标签: java split duplicates


【解决方案1】:

可以使用distinct()流的操作

Arrays.stream(duplicates.split("\\s+(-|–|‒|–|—|―)+\\s+")) // split by different types of dashes surrounded by whitespaces
      .distinct()        // get rid of duplicates
      .collect(Collectors.toList())
      .forEach(System.out::println); // print each entry

输出:

Smith, John
Wilson, Peter

或者使用Collectors.joining得到一个没有重复的字符串:

String duplicates = "Smith, John -- Smith, John - Smith, John – Wilson, Peter ‒ Yves Saint-Laurent ― George Henry Lane-Fox Pitt-Rivers";

String noDuplicates = Arrays.stream(duplicates.split("\\s+(-|–|‒|–|—|―)+\\s+"))
                            .distinct()
                            .collect(Collectors.joining(" – "));
System.out.println(noDuplicates);

打印:

Smith, John – Wilson, Peter – Yves Saint-Laurent – George Henry Lane-Fox Pitt-Rivers

我更新了对可以包含单个连字符的名称的检测以处理非常流行的“双管”名称,并添加了dashes的类型

【讨论】:

  • 我有一个简单的问题......为什么使用 ("-|–") ?
  • 如果您的输入字符串包含不同类型的破折号/连字符 - 在您的输入字符串中至少有两种类型:"-" 和 "–"。您可以在我的示例中检查更新的输入字符串。
  • 我要关闭它吗?不知道如何
  • 意义?你可以接受我的回答 - 打一个绿色的勾
  • @Guisselle 您可能对接受应答机制感兴趣。请看"How does accepting an answer work?"
猜你喜欢
  • 2021-01-14
  • 1970-01-01
  • 2016-04-19
  • 2019-09-02
  • 1970-01-01
  • 1970-01-01
  • 2013-11-12
  • 2012-05-09
  • 1970-01-01
相关资源
最近更新 更多