//编写函数Str_cat(),其功能是将字符串str2连接到字符串str1的第k个字符后面 //在主函数中输入str1,str2和k的值,调入函数Str_cat后,输出str1. #include <stdio.h> #include <stdlib.h> #include <string.h>
#define MAXCHARACTER 100
static char str1[MAXCHARACTER]; static char str2[MAXCHARACTER];
void Str_cat(int);
void Str_cat(int k) { int str_1_length; int str_2_length; char *before_str; char *after_str; str_1_length=strlen(str1); str_2_length=strlen(str2); before_str=(char *)malloc((str_1_length+str_2_length+1)*sizeof(char)); if(!before_str) exit(1); for(int j=0;j<k;j++) before_str[j]=str1[j]; before_str[j]='\0'; after_str=(char *)malloc((str_1_length-k+1)*sizeof(char)); for(int i=k;i<str_1_length;i++) after_str[i-k]=str1[i]; after_str[i-k]='\0'; strcat(before_str,str2); strcat(before_str,after_str); printf("The string afer Str_cat is:\n"); puts(before_str); free(before_str); free(after_str); }
void main() { int k; printf("please enter the first string:\n"); gets(str1); fflush(stdin); printf("please enter the second string:\n"); gets(str2); fflush(stdin); do{ printf("pleas enter the positon(1~%d):\n",strlen(str1)); scanf("%d",&k); fflush(stdin); }while(k>strlen(str1)||k<1); Str_cat(k); } //你先看看 把 //不懂的话,再聊把