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

Time:04-10

This is the code that I came up with, but sometimes it does not work.

For example, if string1 = highway to hell, and string2 = stairway to heaven, the output is 'ghll' despite 'h' being in the second string as well as the first string. I cant figure out why h is not being removed like other characters that are in both strings.

#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);
}

CodePudding user response:

  1. Use a lookup table to efficiently apply character filter.
#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] = '\0';
    printf ("S1 after S2 filter : %s\n", s1);

    return 0;
}
  1. gets() has been deprecated, use fgets() instead.

  2. fgets() : If a newline(\n) is read, it is stored into the buffer. Trim the buffer before use : Removing trailing newline character from fgets() input

  • Related