C字符串插入函数

char* strins(char* dest, const char* src, int pos)
{
    int len = strlen(src);
    for (int i = strlen(dest); i >= pos; i--)
        dest[i + len] = dest[i];    // 同时也拷贝字符串结束符
    for (int j = pos; j < pos + len; j++)
        dest[j] = src[j - pos];
    return dest;
}

另一种方法:

void insert(char *s, char *t, int i)
{
	char *q = t;
	char *p = s;
	if (q == NULL) return;
	while (*p != '\0')
	{
		if (0 >= --i)
		{
			memmove(p + strlen(t), p, strlen(p));
			break;
		}
		p++;
	}
	while (*q != '\0')
	{
		*p = *q;
		p++;
		q++;
	}
}

貌似再优化也需要2次循环,一次将插入位置后的子串后移,一次将新子串赋值到插入位置。

需要注意的是内存溢出的问题,目标字符串必须有足够的空间。

转载于:https://www.cnblogs.com/edwardcmh/archive/2012/05/04/2483019.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值