strcat函数是c语言字符串的连接函数,他的功能是将字符串2拼接到字符串1的后面,但是这道题要求不能使用strcat函数,下面来看看如何解!

首先我们得知:

char str1[30]="hello";

char ste2[]="world";

连接完成后:

char str1[30]="helloworld";

答案:

#include<stdio.h>
int main(){
    char str1[30]="hello";
    char str2[]="world";
    for(int i=5,j=0;str2[j]!='\0';i++,j++){
    str1[i]=str2[j];
    }
    printf("%s",str1);
    return 0;
}

这个过程用白话文来讲:

我们定义i=5是str1的第五位,j=0为str2的第0位开始,因为字符串用\0结束,所以当str2[j]不是最后一位的时候,一直执行str1[i]=str2[j]就是从str2的第五位开始,赋值完继续+1赋值,直到最后遇到\0结束!

例题:输入俩个字符串(<40个字符),连接后输出(不准使用系统函数)。

#include<stdio.h>
int main(){
    char s1[40],s2[40];
    int i,j;
    gets(s1);
    gets(s2);
    for(i=0;i<40;i++);
    for(j=0;j<40;i++,j++)
    s1[i]=s2[j];
    s1[i]='\0'; 
    puts(s1); 
}
End
最后修改:2021 年 05 月 14 日
如果觉得我的文章不错,请随手点赞~