The C Programming Language 练习题2-4

时间:2022-03-31 00:14:05

题目
squeeze(s1, s2),将字符串s1 中任何与字符串s2 中字符匹配的字符都删除。

题目分析
先将s2中每个字符串拿出来在s1中寻找,然后生成不包含此字符的新的s1字符串,然后再找下一个。

编程实现
为了方便定位问题,加的打印信息较多。。。。(其实已经删掉许多打印了)

#include <stdio.h>
#define MAXLINE 1000

void squeeze(char s1[], char s2[]);

int main()
{
    int i;
    char c, sfirst[MAXLINE], ssecond[MAXLINE];

    i = 0;
    printf("Please input string1:");
    while ((c = getchar()) != '\n')
        sfirst[i++] = c;
    sfirst[i] = '\0';
    printf("The first string is:");
    i = 0;
    while (sfirst[i] != '\0')
        printf("%c", sfirst[i++]);
        printf("\n");

    i = 0;
    printf("Please input string2:");
    while ((c = getchar()) != '\n')
        ssecond[i++] = c;
    ssecond[i] = '\0';
    printf("The second string is:");
    i = 0;
    while (ssecond[i] != '\0')
        printf("%c", ssecond[i++]);
        printf("\n");

    squeeze(sfirst, ssecond);
    i = 0;
    while (sfirst[i] != '\0')
    {
        printf("%c",sfirst[i]);
        i++;
    }
}

void squeeze(char s1[], char s2[])
{
    int m, n, l;

    m = n = l = 0;
    for (n = 0; s2[n] != '\0'; n++)
        {
            for (m = l = 0; s1[m] != '\0'; m++)
                if (s1[m] != s2[n])
                    s1[l++] = s1[m];
            s1[l] = '\0';
        }
}