首頁  >  文章  >  後端開發  >  如何刪除字串中的子字串

如何刪除字串中的子字串

零到壹度
零到壹度原創
2018-03-29 15:41:182920瀏覽

本文主要為大家分享一篇如何刪除字串中的子字串的問題,具有很好的參考價值,希望對大家有所幫助。一起跟著小編過來看看吧。

話不多說,直接上程式碼。

演算法思想: 找到要刪除的第i個結點,逐一刪除。

#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())!=&#39;\n&#39;)
    {
        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;

}

相關推薦:

刪除指定字串中的子字串

在字串中刪除子字串

刪除字串中的子字串

以上是如何刪除字串中的子字串的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn