Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates from String

Tags:

java

string

Here is my code,

   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;
}

I want to remove duplicate entries from the string "date" which is being return. Dates[] and Month[] are static int arrays. Can anybody help me?

The output I'm getting is this:

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|

and I want this:

25-5|28-5|4-6|8-6|10-6|14-6|17-6|7-7|26-7| 
like image 527
Soniya Avatar asked Jan 17 '26 23:01

Soniya


2 Answers

Instead of concatenating dates to a string, add your dates to a Set as you loop over the records. Sets cannot contain duplicates.

Then at the end of the method, loop over your set and construct a string to return.

like image 57
dogbane Avatar answered Jan 19 '26 13:01

dogbane


You could assemble a Set of strings that will be concatenated after the set is populated.

Edit: ah, dogbane got there first :P

like image 28
Samthere Avatar answered Jan 19 '26 15:01

Samthere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!