w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Combining two strings removing duplicate substrings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *combine (const char *nodehashkey, const char *ngbrhashkey){
    int i, dup, len, pos_count = 0;
    const char *p1, *p2, *pos[64];
    char *combo_hashkey, *p3;

    if(!nodehashkey || !ngbrhashkey)
        return NULL;

    //store key position
    pos[0] = p1 = nodehashkey;
    while(*p1){
        sscanf(p1, "#%*d#%*[.0123456789]%n", &len);
        pos[++pos_count] = (p1 += len);
    }
    len = p1 - nodehashkey;
    p2 = ngbrhashkey;
    p3 = combo_hashkey = malloc(len + strlen(p2) + 1);
    memcpy(p3, nodehashkey, len);
    p3 += len;
    while(*p2){
        sscanf(p2, "#%*d#%*[.0123456789]%n", &len);
        for(dup=i=0;i<pos_count;++i){
            if(pos[i+1]-pos[i] == len && strncmp(pos[i], p2,
len)==0){
                dup = 1;
                break;
            }
        }
        if(!dup){
            memcpy(p3, p2, len);
            p3 += len;
        }
        p2 += len;
    }
    *p3 = '';
    return combo_hashkey;
}

int main(){
    char *str1, *str2, *str3;
    str1 = combine("#1#.1.2.3#1#.6.7.8", "#1#.6.7.8#1#.5.6");
    printf("%s
", str1);//#1#.1.2.3#1#.6.7.8#1#.5.6
    free(str1);

    str2 = combine("#1#.1.6", "#1#.2.4");
    str3 = combine("#1#.1.6", "#1#.3.5");
    printf("str2:%s
", str2);
    printf("str3:%s
", str3);

    char *weird = combine(str2, str3);

    printf("weird: %s
", weird);//weird: #1#.1.6#1#.2.4#1#.3.5
    free(str2);free(str3);free(weird);
    return 0;
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.