用指针编写函数 : insert(s1,s2,f), 其功能是在字符串s1中的指定位置f处(f为整数,值从1开始)插入字符串s2。
函数中先计算两个字符串长度,如果插入位置超出了范围,则输出错误提示。否则,利用temp数组保存f位置之后的原字符串,然后将s2复制到s1中f的位置处,最后将temp中的内容接在s2之后即可。
#include <stdio.h>
#include <string.h>
void insert(char *s1, char *s2, int f)
{
int len1 = strlen(s1);
int len2 = strlen(s2);
if (f > len1 + 1) {
printf("Error: insert position is out of range.\n");
return;
}
char temp[len1 - f + 1];
strcpy(temp, s1 + f - 1);
strcpy(s1 + f - 1, s2);
strcpy(s1 + f - 1 + len2, temp);
}
int main()
{
char s1[100], s2[100];
int f;
printf("Enter the string s1: ");
fgets(s1, 100, stdin);
printf("Enter the string s2: ");
fgets(s2, 100, stdin);
printf("Enter the position f: ");
scanf("%d", &f);
insert(s1, s2, f);
printf("The result string is: %s\n", s1);
return 0;
}
如果以上回答对您有所帮助,点击一下采纳该答案~谢谢