简体   繁体   中英

Recursive function s: Remove substring from string in C

So I'm supposed to write a program that removes every occurence of substring p from string s, and then print it, using a recursive function, and I'm all out of ideas, so if anyone knows how, let me know. This is as far as I've got:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
void remove(char *s, char *p)
{
    char *c=strstr(s,p);
    if(c == 0)
        return;

}
int main()
{
    char s[100], p[50];
    printf("Enter string and substring: ");
    scanf("%s %s", s, p);
    remove(s, p);
    printf("New string: %s", s);
    getchar();
    getchar();
    return 0;
}

This should work:

#include <stdio.h>
#include <string.h>
void removestr(char *s, char *p, int len)
{
    char *c=strstr(s,p); // strstr returns the address where the substring starts
    if(c) {
      strcpy(c,c+len); //if the substring was found, copy over it the 
 //string starting from where the substring ends e.g. (assume    
//p="the") thisthestring => thisstring
      removestr(s,p,len); //call the function again
    }
    else
      return;  //stop if no substring was found

}
int main(void)
{
    char s[100], p[50];
    printf("Enter string and substring: ");
    if(scanf("%99s",s)==1 && scanf("%49s",p)==1) //it's important to check the input
// also %s is vulnerable to overflow, specify the sizes to be safe
      removestr(s, p , strlen(p));
    printf("New string: %s", s);
    getchar();
    getchar();
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM