首页 > 试题广场 >

编一程序,将两个字符串连接起来,不要用strcat函数。

[问答题]
编一程序,将两个字符串连接起来,不要用strcat函数。
推荐

#include<stdio.h>

int main()

{char s1[80],s2[40];

int i=0,j=0;

printf("input string1:");

scanf("%s",s1);

printf("input string2:");

scanf("%s",s2);

while(s1[i]!=’\0’)

i++;

while(s2[j]!=’\0’)

s1[i++]=s2[j++]:

s1[i]=’\0’;

printf(“\nThe new string is:%s\n”,s1);

return 0;

}


发表于 2018-03-25 10:37:33 回复(0)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* connect(char line1[], char line2[]){
 int length1 = strlen(line1);
 int length2 = strlen(line2);
 const int total = length1 + length2;
 char* result = malloc(sizeof(char) * total);
 for(int i = 0; i < length1; i ++){
  result[i] = line1[i];
 }
 for(int i = length1, j = 0; i < total && j < length2; i ++, j ++){
  result[i] = line2[j];
 }
 result[total] = 0;
 return result;
}
int main(){
 char line1[20];
 char line2[20];
 scanf("%s", line1);
 scanf("%s", line2);
 int length1 = strlen(line1);
 int length2 = strlen(line2);
 const int total = length1 + length2;
 char* result = connect(line1,line2);
 char* result2 = strcat(line1,line2);
 char* result3 = malloc(sizeof(char) * total);
 memcpy(result3,line1,sizeof(char) * length1);
 memcpy((result3 + length1),line2,sizeof(char) * length2);
 puts(result);
 puts(result2);
 puts(result3);
}
编辑于 2020-01-01 16:45:16 回复(0)