Đăng nhập để hỏi chi tiết


Hãy luôn nhớ cảm ơn và vote 5*
nếu câu trả lời hữu ích nhé!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void concatenateStrings(char *str1, char *str2, char *result) {
while (*str1) {
*result++ = *str1++;
}
while (*str2) {
*result++ = *str2++;
}
*result = '\0';
}
int main() {
char str1[100], str2[100], *result;
printf("Nhập chuỗi thứ nhất: ");
fgets(str1, sizeof(str1), stdin);
str1[strcspn(str1, "\n")] = 0;
printf("Nhập chuỗi thứ hai: ");
fgets(str2, sizeof(str2), stdin);
str2[strcspn(str2, "\n")] = 0;
result = (char *)malloc(strlen(str1) + strlen(str2) + 1);
if (result == NULL) {
printf("Không đủ bộ nhớ!\n");
return 1;
}
concatenateStrings(str1, str2, result);
printf("Chuỗi nối: %s\n", result);
free(result);
return 0;
}
Hãy giúp mọi người biết câu trả lời này thế nào?
`C`
`" "`
#include <stdio.h>
#include <string.h>
void noi(char *s1, char *s2) {
s1 += strlen(s1);
while(*s2)
*s1++ = *s2++;
*s1 = '\0';
}
int main() {
char s1[100], s2[50];
printf("Nhap chuoi 1: ");
fgets(s1, sizeof(s1), stdin);
s1[strcspn(s1, "\n")] = '\0';
printf("Nhap chuoi 2: ");
fgets(s2, sizeof(s2), stdin);
s2[strcspn(s2, "\n")] = '\0';
noi(s1, s2);
printf("Sau khi noi: %s\n", s1);
return 0;
}
`" "`
`-` s1 += strlen(s1): Dịch con trỏ s1 tới vị trí '\0' cuối chuỗi 1, tức là chỗ sẽ bắt đầu nối
`-` while(*s2): Lặp khi s2 chưa đến '\0', tức là chưa hết chuỗi 2
`-` *s1++ = *s2++: Sao chép từng ký tự từ s2 sang s1, rồi tiến cả hai con trỏ
`-` *s1 = '\0': Thêm ký tự kết thúc chuỗi sau khi nối xong
Hãy giúp mọi người biết câu trả lời này thế nào?
Bảng tin