从String中删除重复项

时间:2011-08-16 10:43:07

标签: java string

这是我的代码,

   public static String set_x_dates()
   {
    int noRecords = GlobalData.getNoRecords();
    int n;
    String date = "";
    if (noRecords <= 10)
        for (n = 0; n < noRecords; n++)
            date += Dates[n] + "-" + Month[n] + "|";
    else {
        for (n = 0; n < noRecords; n++) {
            int gap = (int) (noRecords / 10);
            date += Dates[n] + "-" + Month[n] + "|";
            n++;
            if (n != noRecords)
                for (; gap > 0; gap--)
                    date += "|";
        }

    }
    return date;
}

我希望从正在返回的字符串“date”中删除重复的条目。日期[]和月[]是静态int数组。有人能帮助我吗?

我得到的输出是:

25-5|28-5|4-6|8-6|10-6|14-6|17-6|7-7|7-7|7-7|7-7|7-7|7-7|7-7|7-7|7-7|7-7|26-7|26-7|

我想要这个:

25-5|28-5|4-6|8-6|10-6|14-6|17-6|7-7|26-7| 

3 个答案:

答案 0 :(得分:8)

不是将日期连接到字符串,而是在循环记录时将日期添加到Set。集不能包含重复项。

然后在方法结束时,循环遍历集合并构造一个字符串以返回。

答案 1 :(得分:1)

您可以汇编Set个字符串,这些字符串将在填充集合后连接。

编辑:啊,狗狗首先到达那里:P

答案 2 :(得分:0)

以下是删除String中重复项的代码。

enter image description here

输出:

enter image description here

相关问题