Home > Article > Backend Development > How to remove substring from string
This article mainly shares with you an article on how to delete substrings in a string. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor to have a look.
Without further ado, let’s get straight to the code.
Algorithm idea: Find the i-th node to be deleted and delete it one by one.
#include <stdio.h> #include <stdlib.h> typedef char datatype; typedef struct node{ datatype x; struct node *next; }seqlist; // 创建带头结点的单链表 seqlist *creat() { seqlist *p,*s,*head=NULL; datatype ch; head=(seqlist *)malloc(sizeof(seqlist)); p=head; head->next=NULL; while((ch=getchar())!='\n') { s=(seqlist *)malloc(sizeof(seqlist)); s->x=ch; p->next=s; p=s; } p->next=NULL; return head; } // 单链表的遍历1 seqlist * display1(seqlist *head) { seqlist *p; p=head->next; while(p) { printf("%c",p->x); p=p->next; } printf("\n"); return head; } // 单链表的遍历2 创建这个是因为返回值为null时用1会造成错误。 seqlist * display2(seqlist *head) { seqlist *p; p=head; while(p) { printf("%c",p->x); p=p->next; } printf("\n"); return head; } // 字符串子串的删除 seqlist * Del(seqlist * head,int i,int len) { seqlist *p,*q,*r; // p,q,r 分别为移动,替死符,记录前一个位子。 int k=1; p=r=head; while(p && k<=i) { r=p; p=p->next; k++; } if(!p) { printf("Error1\t 位置超出范围\n"); return (NULL); } else { k=1; while(p && k<=len) //这里需要特别注意出口条件 { if(p==r) { p=p->next; q=p; p=q->next; r->next=q->next; k++; free(q); } else { q=p; p=q->next; r->next=q->next; k++; free(q); } } if(k<len) { printf("Error 2\t长度超出范围\n"); return (NULL); } else return head; } } int main() { int i,len; seqlist *head; head=creat(); display1(head); scanf("%d",&i); scanf("%d",&len); head=Del(head,i,len); display2(head); return 0; }
Related recommendations:
Delete the substring in the specified string
Delete in the string Substring
The above is the detailed content of How to remove substring from string. For more information, please follow other related articles on the PHP Chinese website!