How to remove duplicate values in a string

Ram Prashanth

New Member
I have a char variable which holds "a,b,c,d,a,b,c,d".
Is there any built-in function which removes the duplicates and just returns me "a,b,c,d".
 
Hi Ram
Nope, it does not exist, you will have to code it yourself.
Depending on the possible length of the list, I would do it with an iteration on the list, creating the output on the fly, or if the list can grow big, using a temp-table to store the unique items, then create the output from there.
++
 

Ashwani Mishra

New Member
This should help :)

Code:
/********** Option 1 ************/

DEFINE VARIABLE cList AS CHARACTER   NO-UNDO INIT "a,b,c,d,a,b,c,d".

DEFINE TEMP-TABLE ttUnique
      FIELDS Listitem AS CHAR.
      
FUNCTION getUniqueList RETURN CHAR (INPUT cList AS CHAR) FORWARD.

MESSAGE  "Option 1 : " SKIP
         getUniqueList("a,b,c,d,a,b,c,d")
    VIEW-AS ALERT-BOX INFORMATION BUTTONS OK.

FUNCTION getUniqueList RETURNS CHAR (INPUT cList AS CHAR):
    DEFINE VARIABLE cResult AS CHARACTER   NO-UNDO.
    DEFINE VARIABLE icnt AS INTEGER     NO-UNDO.
    
    DO icnt = 1 TO NUM-ENTRIES(clist):
        FIND FIRST ttunique WHERE ttunique.ListItem = TRIM(ENTRY(icnt,cList)) NO-ERROR.
        IF NOT AVAILABLE ttunique THEN
        DO:
            CREATE ttunique.
            ASSIGN ttunique.ListItem = TRIM(ENTRY(icnt,cList)).
        END.
    END.
    
    FOR EACH ttunique:
        cresult = IF cResult = "" THEN
                    ttunique.ListItem
                   ELSE
                    cResult + ","  + ttunique.ListItem.
    END.
    
    RETURN cResult.
END FUNCTION.



/********** Option 2 ************/

FUNCTION getUniqueList2 RETURN CHAR (INPUT cList AS CHAR) FORWARD.

MESSAGE  "Option 2 :" SKIP
         getUniqueList2("a,b,c,d,a,b,c,d")
    VIEW-AS ALERT-BOX INFORMATION BUTTONS OK.

FUNCTION getUniqueList2 RETURNS CHAR (INPUT cList AS CHAR):
    DEFINE VARIABLE cResult AS CHARACTER   NO-UNDO.
    DEFINE VARIABLE icnt AS INTEGER     NO-UNDO.
    
    DO icnt = 1 TO NUM-ENTRIES(clist):
        CREATE ttunique.
        ASSIGN ttunique.ListItem = TRIM(ENTRY(icnt,cList)).
    END.
    
    FOR EACH ttunique BREAK BY ttunique.ListItem:
    
        IF FIRST-OF(ttunique.ListItem) THEN
        DO:
            cresult = IF cResult = "" THEN
                    ttunique.ListItem
                   ELSE
                    cResult + ","  + ttunique.ListItem.   
        END.
    END.
    
    RETURN cResult.
END FUNCTION.
 
source = ‘a,b,c,d,a,b,c,d”.

do i = 1 to num-entries(source):

if lookup(entry(i,source), dest)) = 0 then

dest = dest + "," + entry(i,source).

end.
 
Top