编写算法,实现下面函数的功能。函数void insert(char *s, char *t, int pos)将字符串t插入到字符串s中,插入位置为pos。假设分配给字符串s的空间足够让字符串t插入


void Insert(char *s, char *t, int pos)//将字符串t插入到字符串s的pos位置中,pos最小值为0
{
	int i,j, len_s,len_t, move_len;
	char *ptr, *ptr_s;

	i = 0;
	j = 0;
	len_s = 0;
	len_t = 0;

	for(ptr = s; *ptr != '\0'; ptr++)
	{
		len_s++;//不包含'\0'
	}
	for(ptr = t; *ptr != '\0'; ptr++)
	{
		len_t++;//不包含'\0'
	}

	move_len = len_s - pos + 1;//s[]中需要后移的数组元素个数,包含'\0'
	s = (char*)realloc(s, len_s + len_t + 1);
	for(ptr = s + len_s, i = 1; i <= move_len; i++)// 将s中被插入位置及之后的元素全部后移,为t空出位置,i == move_len时将s的'\0'移动至新字符串末尾
	{
		*(ptr + len_t) = *ptr;
		*ptr = 'F'; //
		ptr--;
	}
	cout<<"后半截移动后的s:"<

 

你可能感兴趣的:(数据结构基础)