-6

I want to create a function called remstr(). This function removes a given string from another string without using string.h. Example:

 str1[30]= "go over stackover"
 str2[20]= "ver"
 strrem[20]= "go o stacko"

Please help me

MOHAMED
  • 41,599
  • 58
  • 163
  • 268

3 Answers3

2

C gives you lots of useful building blocks for doing this. In particular, you can build this function using three standard library functions: strstr (to find the string you want to remove), strlen to compute the length of the rest of the string, and memcpy to copy the parts you don't want to delete into the destination (you'll need to use memmove instead of memcpy if you want the function to operate in place). All three functions are declared in <string.h>.

Take a crack at writing the function, and ask specific questions if and when you run into trouble.

Stephen Canon
  • 103,815
  • 19
  • 183
  • 269
0
#include <stdio.h>
#include <stdlib.h>

void remstr(char *str1, char *str2, char *strrem)
{
    char *p1, *p2;
    if (!*str2) return;
    do {
        p2 = str2;
        p1 = str1;
        while (*p1 && *p2 && *p1==*p2) {
            p1++;
            p2++;
        }
        if (!(*p2)) str1 = p1-1;
        else *strrem++ = *str1;
    } while(*str1 && *(++str1));
    *strrem = '\0';
}


int main() {

    char str1[30]= "go over stackover";
    char str2[20]= "ver";
    char strrem[30];
    remstr(str1, str2, strrem);
    printf("%s\n",strrem);
}

with this function you can even put the result in the same string buffer str1:

remstr(str1, str2, str1);
printf("%s\n",str1);
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
0

The pseudo code is pretty straight forward for what you want to do, and if you can't use string.h functions then you just have to recreate them.

char * remstr(char *str1, char * str2)
{
    get length of str1
    get length of str2
    for(count from 0 to length of str2 - length of str1) {
       if ( str1[count] != str2[count])
          store str2[count] in to your new string
       else
          loop for the length of str1 to see if all character match
            hold on to them in case they don't and you need to add them into you
            new string
    }
    return your new string
}

You need to figure out the details, does remstr() allocate memory for the new string? Does it take an existing string and update it? What is the sentinel character of your strings?

You'll need a strlen() for this to work, since you can't use it you need to make something like:

int mystrlen(char* str) {
    while not at the sentinel character
      increment count
    return count
}
Mike
  • 47,263
  • 29
  • 113
  • 177