edwardcmh

人氣不過肥皂泡

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
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次循环,一次将插入位置后的子串后移,一次将新子串赋值到插入位置。

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

posted on 2012-05-04 17:10  edwardcmh  阅读(1869)  评论(0编辑  收藏  举报