[ create a new paste ] login | about

Link: http://codepad.org/z5m9M4Fp    [ raw code | output | fork ]

mdo - C++, pasted on May 5:
#include <set>
#include <string.h>

typedef std::set<char> ChSet;
typedef std::set<char>::iterator ChSetIter;

/* Remove all the duplicate chars from the given string in-place */
void dedupe_string(char *str, int sz)
{
    ChSet cset;
    ChSetIter csiter;
    int lastpos = -1;
    
    for (int i = 0; i < sz; i++){
        char ch = str[i];
        csiter = cset.find(ch);
    
        if (csiter == cset.end()) { // Unique char
            cset.insert(ch);
            if (-1 == lastpos) {
                continue; // means we do not have previous holes
            }
            else {
                str[lastpos] = ch; // move our unique char to fill the gap
                str[i] = '\0'; // create a hole in place of the dup char
                lastpos++;
            }
        }
        else { // Found duplicate char
            printf("%c ", ch);
            if (-1 == lastpos)
                lastpos = i;
            else {
                str[i] = '\0';
            }
        }        
    }
    printf("\n");
}

int main(int argc, char* argv[])
{
    //char str[] = "abracadabra";
    char str[] = "madam_i_am_adam"; // a palindrome
    int sz = strlen(str);
    
    printf("BEFORE: %s\n", str);
    dedupe_string(str, sz);
    printf("AFTER: %s\n", str);    
    return 0;
}


Output:
1
2
3
BEFORE: madam_i_am_adam
a m _ a m _ a d a m 
AFTER: mad_i


Create a new paste based on this one


Comments: