【问题标题】:Recursive function s: Remove substring from string in C递归函数s:从C中的字符串中删除子字符串
【发布时间】:2016-07-04 12:07:46
【问题描述】:

所以我应该编写一个程序,从字符串 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;
}

【问题讨论】:

  • 让我们从一个删除子字符串once的函数开始。婴儿步。
  • 这真的不是很递归的atm。想想你在下一次迭代中推进了什么,以及下一次递归回来后你对结果做了什么。
  • 嗯,这就是我遇到的问题,我知道的基本情况,但是如果不满足该怎么办

标签: c arrays string recursion substring


【解决方案1】:

这应该可行:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 2011-10-15
    • 2020-10-28
    • 1970-01-01
    • 2019-09-08
    相关资源
    最近更新 更多