繁体   English   中英

递归函数 s:从 C 中的字符串中删除子字符串

[英]Recursive function s: Remove substring from string in C

所以我应该编写一个程序,从字符串 s 中删除子字符串 p 的每个出现,然后使用递归函数打印它,我完全没有想法,所以如果有人知道如何,请告诉我。 就我而言,这是:

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

这应该有效:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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