字符串:指定位置插入

输入字符串s、t,将字符串t插入到字符串s中

/* **************************
编写程序,定义函数 void insert(char *s, char *t, int pos) 将字符串t插入到
字符串s中,插入位置为pos。假设分配给字符串s的空间足够让字符串t插入。
*************************** */

#include <stdio.h>
#include <string.h>

#define MAXLEN 40
#define FALSE 0
#define OK 1

//定义顺序串1
typedef struct {
    char ch1[MAXLEN];
    int len1;
} SString1;

//定义顺序串2
typedef struct {
    char ch2[MAXLEN];
    int len2;
} SString2;

//插入
int Insert(SString1 *s, SString2 t, int pos) {
    int i;

    if (pos < 0 || pos > s->len1) {
        printf("\t插入位置不合法!");
        return FALSE;
    }

    if (s->len1 + t.len2 <= MAXLEN) { //插入后串长<=MAXLEN
        for (i = s->len1 + t.len2 - 1; i >= t.len2 + pos; i--)
            s->ch1[i] = s->ch1[i - t.len2];
        for (i = 0; i < t.len2; i++)
            s->ch1[i + pos] = t.ch2[i];
        s->len1 = s->len1 + t.len2;
    } else if (pos + t.len2 <= MAXLEN) { //插入后串长>MAXLEN,但串t的字符序列可以全部插入
        for (i = MAXLEN - 1; i > t.len2 + pos - 1; i--)
            s->ch1[i] = s->ch1[i - t.len2];
        for (i = 0; i < t.len2; i++)
            s->len1 = MAXLEN;
    } else { //插入后串长>MAXLEN,并且串t的部分字符也要舍弃
        for (i = 0; i < MAXLEN - pos; i++)
            s->ch1[i + pos] = t.ch2[i];
        s->len1 = MAXLEN;
    }

    printf("%s", s->ch1);
    return OK;
}

//主函数
int main() {
    SString1 s;
    SString2 t;

    int pos;

    printf("请输入字符串s:");
    scanf("%s", s.ch1);
    s.len1 = strlen(s.ch1);
    printf("请输入字符串t:");
    scanf("%s", t.ch2);
    t.len2 = strlen(t.ch2);
    printf("请输入想插入字符串s的位置:");
    scanf("%d", &pos);

    Insert(&s, t, pos - 1);

    return 0;
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值