我有String cat = "cat1, cat1, cat1, cat1, cat2, cat2, cat2, cat3";
我需要String cat = "cat1, cat2, cat3";
怎么做?
这是我的解决方案,但不是很好:
String[] words = cat.split(",");
Arrays.sort(words);
....
答案 0 :(得分:7)
你可以试试这个 -
String cat = "cat1,cat1,cat1,cat1,cat2,cat2,cat2,cat3";
Set<String> set = new HashSet<String>(Arrays.asList(cat.split(",")));
答案 1 :(得分:5)
尝试
String cat = "cat1, cat1, cat1, cat1, cat2, cat2, cat2, cat3";
String text = new TreeSet<String>(Arrays.asList(cat.split(", "))).toString();
String cats = text.substring(1, text.length()-1);
System.out.println(cats);
这将产生你需要的字符串。
cat1, cat2, cat3
答案 2 :(得分:1)
这里:
//hash
HashSet<String> hs = new HashSet<String>();
String[] words = cat.split(",");
for(int i = 0;i < words.length; i++) hs.add(words[i]);
//dehash
StringBuilder builder = new StringBuilder();
Iterator it = hs.iterator();
while(it.hasNext())
{
builder.append(it.next());
builder.append(",");
}
String dehashed = builder.toString();