【问题标题】:Stripping characters off each element of an array/set in Java从Java中的数组/集合的每个元素中剥离字符
【发布时间】:2015-12-25 05:24:02
【问题描述】:

我有一个打印如下的 HashSet:

[Category:Porch of the Cathedral of Palermo, Category:Side views of the Cathedral of Palermo, Category:Church towers of the Cathedral of Palermo, Category:Saint Rosalia by Vincenzo Vitaliano, Category:Piazza del Duomo (Palermo)]

我需要从集合的每个元素中去除“类别:”字符,以生成输出:

[Porch of the Cathedral of Palermo, Side views of the Cathedral of Palermo, Church towers of the Cathedral of Palermo, Saint Rosalia by Vincenzo Vitaliano, Piazza del Duomo (Palermo)]

执行此操作的最简单方法是什么(在 Java 中)?我目前正在使用 HashSet(需要它来确保元素是唯一的),但我可以将其转换为 ArrayList 或最适合此任务的任何东西。

【问题讨论】:

  • 你试过什么?您应该包括您尝试做的事情,而不是依靠我们立即解决问题。
  • 将元素类的toString()方法改为不前缀"Category:"。或者,编写您自己的字符串化Set 的方法。为什么你还关心? SettoString 用于调试,不用于最终用户显示。
  • @Andreas 我需要稍后使用 Set 向用户显示这些,并且前缀是从外部 API 接收的。但你是对的,我什至应该在将项目添加到集合之前执行此操作。我已经更改了我的代码来执行此操作,但是无论如何 replace(x, y) 方法都非常有用。

标签: java arrays string set


【解决方案1】:

最简单的方法是:将"Category:" 替换为空字符串。您已经在调用toString() 中的HashSet

System.out.println(set.toString().replace("Category:", ""));

输出:

Before: [Category:Side views of the Cathedral of Palermo, Category:Porch of the Cathedral of Palermo]
After: [Side views of the Cathedral of Palermo, Porch of the Cathedral of Palermo]

【讨论】:

  • 谢谢!完美运行。 :)
  • 我尝试这样做,但它告诉我需要再等几分钟。以后会做的!
猜你喜欢
  • 1970-01-01
  • 2020-07-24
  • 2011-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
  • 2017-10-28
相关资源
最近更新 更多