仅使用循环来区分两个字符串

时间:2016-07-27 11:19:25

标签: c algorithm loops diff

编写一个带有两个字符串和显示的程序,没有双打, 出现在其中一个字符串中的字符。

显示将按命令行中出现的字符顺序排列 之后是\n

简而言之,我想做类似的事情:

first string: "zpadinton"
second string: "paqefwtdjetyiytjneytjoeyjnejeyj"

并输出:

output: "zpadintoqefwjy"

其他例子:

string1: "rien" 
string2: "cette phrase ne cache rien"
output: "rienct phas"

string1: "ddf6vewg64f"
string2: "gtwthgdwthdwfteewhrtag6h4ffdhsd"
output: "df6vewg4thras"

我正在尝试做类似的事情:

  char et(char *str, char *str2)
{
    int i;
    int current;
    int check;
    char tmp[strlen(*str) + strlen(*str2)];

    i = 0;
    current = 0;
    check = 0;
    while(*str)
    {
        check = 0;
        while (check != current){
            if (tmp[check] == *str)
                return (0);
            check++;
        }
        if (check == current)
        {
            printf("%c", *str);
            tmp[current] = *str;
            ++check;
        }
        str++;
    }
    while(*str2)
    {
        check = 0;
        while (check != current){
            if (tmp[check] == *str2)
                return (0);
            check++;
        }
        if (check == current)
        {
            printf("%c", *str2);
            tmp[current] = *str2;
            ++check;
        }
        str2++;
    }
    return (0);
}   

但这不起作用。 我怎么做这个?

P.S:我想在不使用函数strcmp strcpyboolean type of date的情况下做到这一点,或类似的事情。

1 个答案:

答案 0 :(得分:-1)

void twodiff(char* s1,char* s2) {
    bool[256] set1; // screw mallocs
    bool[256] set2;
    int i;
    for (i=0;i<256;i++) {
        set1[i]=false;
        set2[i]=false;
    }
    int l1=strlen(s1);
    int l2=strlen(s2);
    for (i=0;i<l1;i++) set1[s1[i]]=true;
    for (i=0;i<l2;i++) set2[s2[i]]=true;
    for (i=0;i<256;i++) set1[i]=set1[i]^set2[i]; // combine sets by xor
    for (i=0;i<l1;i++) {
        if (set1[s1[i]]) {
            set1[s1[i]]=false;
            printf("%c",s1[i]);
        }
    }
    for (i=0;i<l2;i++) {
        if (set1[s2[i]]) {
            set1[s2[i]]=false;
            printf("%c",s2[i]);
        }
    }
}

这假设您希望字符出现在s1 XOR s2中,即只在一个或另一个字符串中出现。如果您需要&#34; s1或s2&#34;,请更改组合条件。

更新:假设您可以更改传递的字符串,您可以简单地替换您已经通过处理中跳过的符号输出的所有符号。这不是一件好事,但有了这些限制,它将是最简单的方法。

void manglestr(char* s1, char* s2) {
    char mangler;
    int i;
    int j;
    int l1=strlen(s1);
    int l2=strlen(s2);
    if (0==l1) mangler=s2[0]; else mangler=s1[0];
    printf("%c",mangler);
    for (i=0;i<l1;i++) {
        if (s1[i]!=mangler) {
            printf("%c",s1[i]);
            for (j=i1+1;j<l1;j++) if (s1[j]==s1[i]) s1[j]=mangler;
            for (j=0;j<l2;j++) if (s2[j]==s1[i]) s2[j]=mangler;
        } // this will ensure we mangle all characters we send to output
    }
    for (i=0;i<l2;i++) {
        if (s2[i]!=mangler) {
            printf("%c",s2[i]);
            for (j=i1+1;j<l2;j++) if (s2[j]==s2[i]) s2[j]=mangler;
        }
    }
}