如何从与另一个字符串中的任何字符匹配的字符串中删除每个字符

How do I delete each character from a string that matches any character in another string

这是我想出的代码,但有时它不起作用。

例如,如果 string1 = 通往地狱的高速公路,string2 = 通往天堂的阶梯,尽管 'h' 在第二个字符串和第一个字符串中,但输出为 'ghll'。我不明白为什么 h 没有像两个字符串中的其他字符一样被删除。

#include <stdio.h>
#include <string.h>
main()
{
    char string1[30], string2[30];
    int length1, length2;

    printf("Enter string 1: ");
    gets(string1);

    printf("Enter string 2: ");
    gets(string2);

    length1 = strlen(string1);
    length2 = strlen(string2);

    for (int i = 0; i <= length1; i++)
    {
        for (int j = 0; j <= length2; j++)
        {
            if (string1[j] == string2[i])
            {
                for (int k = j; k <= length1; k++)
                {
                    string1[k] = string1[k + 1];
                }
            }
        }
    }

    printf("Deleted characters of string 2 from string 1: %s", string1);
}
  1. 使用查找 table 有效地应用字符过滤器。
#include <stdio.h>
#include <string.h>

int main() {
    char s1[] = "highway to hell";
    char s2[] = "stairway to heaven";

    printf ("S1: %s\nS2: %s\n", s1, s2);

    char alt[256] = {0};
    //build a lookup table for efficient filtering
    for (int ci = 0; s2[ci]; )
        alt[(unsigned char)s2[ci++]] = 1;

    int slen = 0;
    for (int ci = 0; s1[ci]; ++ci) {
        if (alt[(unsigned char)s1[ci]]) continue;
        s1[slen++] = s1[ci];
    }
    s1[slen] = '[=10=]';
    printf ("S1 after S2 filter : %s\n", s1);

    return 0;
}
  1. gets() 已弃用,请改用 fgets()

  2. fgets() :如果读取到换行符(\n),则将其存储到缓冲区中。 Trim 使用前的缓冲区:Removing trailing newline character from fgets() input