Jake Z
Jake Z

Reputation: 1133

Removing all occurences of all charactesr from second string in first string

I have a small problem. I have a function that takes in two parameters (two strings). For example: String1 = "hello" String2 = "leo" I need to remove all characters from String2 in String1. In this case, my final result should be: "h". I need to incorporate pointers when doing this! I've got this code so far, but it's only remove "e" from "hello". I don't know why it's not working. If someone has a better or efficient way of doing this, please help!

void rmstr(char str1[], char str2[])
{

//Pointers to traverse two strings
char *p_str1 = &str1[0];
char *p_skip;
int length = (int)strlen(str2); 
int i;

while(*p_str1 != '\0')
{
    for (i = 0; i < length; i++) 
    {
        if(*p_str1 == str2[i])
        {
            for(p_skip = p_str1; *p_skip == str2[i]; ++p_skip);
            memcpy(p_str1, p_skip, &str1[strlen(str1)+1] - p_skip);
        }

        if(*p_str1 != '\0')
        {
            ++p_str1;
        }
    }
}
}

Upvotes: 0

Views: 1924

Answers (2)

CS Pei
CS Pei

Reputation: 11047

Well, this answer has less variables and maybe easier to read.

    #include "stdio.h"

    /* check if c belongs to the second str */
    int char_belong_to_str(char c, char *str)
    {
        while(*str)
            if (c == *str++)
                    return 1;

        return 0;
    }

    void rmstr(char str1[], char str2[])
    {
        int result_len = 0;   /* saves the result str len*/
        char * p_new = str1;

        while (*str1)
        {
            char c = *str1;
            if (!char_belong_to_str(c, str2)) /* if not found in str2, save it*/
            {
                *(p_new + result_len) = c;
                ++result_len;
            }
            ++str1;
        }
        *(p_new+result_len) = '\0';

        printf("%s \n", p_new);
    }

    int main()
    {
        char  p1[] = "hello";
        char  p2[] = "elo";

        rmstr(p1, p2);
        return 0;
    }

Upvotes: 0

Rafi Kamal
Rafi Kamal

Reputation: 4600

char* rmstr(char *str1, char *str2, char *ans) {
    char *p1 = str1;
    char *p2 = str2;
    char *res = ans;

    while (*p1 != '\0') {
        p2 = str2;
        while (*p2 != '\0') {
            if (*p1 == *p2)    // A character in str1 is found inside str2
                break;
            p2++;
        }
        if (*p2 == '\0') {   // No match found
            *ans = *p1;
            ans++;
        }
        p1++;
    }
    *ans = '\0';
    return res;
}

Testing code:

int main(void) {
    char str1[] = "hello";
    char str2[] = "elo";
    char ans[10];

    printf(rmstr(str1, str2, ans));

    return 0;
}

Upvotes: 1

Related Questions