gpt4 book ai didi

C 将两个小字符串连接成一个大字符串

转载 作者:行者123 更新时间:2023-11-30 15:21:17 25 4
gpt4 key购买 nike

我正在尝试创建一个将两个字符串连接在一起的程序。我的代码创建了一个 char[],它由两个字符串进行 strcat 编辑。结果是令人困惑的垃圾。知道发生了什么吗?我想象当我尝试concat时,char[]已经充满了垃圾,但我不确定。

#include <stdio.h>
#include <string.h>

int main(){
char* s1 = "this";
char* s2 = "that";
char s3[9];

int i;

for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
strcat(s3, s1);
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
strcat(s3, s2);
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
}

输出:

@



@
t


@
t

最佳答案

您必须设置 s3[0] = '\0';或者您必须使用 strcpy 作为第一个。

s3[0] = '\0';

#include <stdio.h>
#include <string.h>

int main(){
char* s1 = "this";
char* s2 = "that";
char s3[9];
int i;

s3[0] = '\0';

for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
strcat(s3, s1);
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
strcat(s3, s2);
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
}

strcpy

#include <stdio.h>
#include <string.h>

int main(){
char* s1 = "this";
char* s2 = "that";
char s3[9];

int i;

for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
strcpy(s3, s1);
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
strcat(s3, s2);
for(i = 0; i < 4; i++){
printf("%c\n", s3[i]);
}
}

关于C 将两个小字符串连接成一个大字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29595840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com