C 将两个小字符串连接成一个大字符串
C concat two small strings to one larger string
我正在尝试创建一个将两个字符串连接在一起的程序。
我的代码创建了一个 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] = '[=10=]';
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]);
}
}
我正在尝试创建一个将两个字符串连接在一起的程序。
我的代码创建了一个 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] = '[=10=]';
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]);
}
}