C语⾔实现:将⼀个字符串插⼊到另⼀个字符串的指定位置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");
return0;
}
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];     //将原数组所有元素赋给新的数组S4
}
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");
return0;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。