C语言实现:将一个字符串插入到另一个字符串的指定位置

示例一:

char *insert(char *s1, char *s2, int n)
{
	int len1 = 0, len2 = 0, j = 0, len3, k = 0;
	char s4[30];
	char *s3 = s4;
	if (s1 == NULL)
		return NULL;
	if (s2 == NULL)
		return s1;
	len1 = strlen(s1);
	len2 = strlen(s2);
 
	if(n>len1)
		return NULL;
	for (int i = 0; i<n; i++) 
	{ 
		j++; 
	}
	for (int i= 0; i<len1; i++)
	{ 
		s4[k++] = s1[i];
	}

	for (int i = 0; i<len2; i++)
		s1[j++] = s2[i];
	  
	for(int i=n;i<len1;i++)
		s1[j++]=s4[i];

	s1[j] = '\0';
	

	return s1;
}

int main(void)
{

	char *s1 = (char*)malloc(20 * sizeof(char));
	char *s2 = (char*)malloc(20 * sizeof(char));
	int n;
	char s3[30];
	char *newstr = s3;
	printf("请输入第一个字符串:");
	scanf("%s", s1);
	printf("请输入第二个字符串:");
	scanf("%s", s2);
	printf("请输入插入的位置:");
	scanf("%d", &n);
	newstr = insert(s1, s2, n);
	printf("%s\n", newstr);

	getchar();
	system("pause");
	return 0;
}

结果:

示例二:插入后原字符串后面的字符去掉了

void Insert(char* s1, char* s2, int n)
{
	char *result = (char*)malloc(20 * sizeof(char));
	char *temp = result;//保存result的初始地址,因为后面要改变result
						//把s1的一部分赋给result
	for (int i = 0; i<n; i++)
	{
		*result = *(s1++);
		result++;
	}
	//把s2的所有内容赋给result
	while (*s2 != '\0')
	{
		*result = *(s2++);
		result++;
	}
	*result = '\0';//字符串结束符
	printf("%s\n", temp);
}

int main()
{
	char *s1 = (char*)malloc(20 * sizeof(char));
	char *s2 = (char*)malloc(20 * sizeof(char));
	int n;
	printf("请输入第一个字符串:");
	scanf("%s", s1);
	printf("请输入第二个字符串:");
	scanf("%s", s2);
	printf("请输入插入的位置:");
	scanf("%d", &n);
	Insert(s1, s2, n);

	getchar();
	system("pause");
	return 0;
}

 结果:

相关推荐
©️2020 CSDN 皮肤主题: 成长之路 设计师:Amelia_0503 返回首页