不用strcat函数使用for循环合并两个字符串
下面是一个使用for循环合并两个字符串的示例代码:
#include <stdio.h>
int main() {
char str1[100], str2[100];
int i, j;
printf("Enter the first string: ");
scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
// 找到第一个字符串的末尾
for (i = 0; str1[i] != '\0'; i++);
// 将第二个字符串追加到第一个字符串的末尾
for (j = 0; str2[j] != '\0'; i++, j++) {
str1[i] = str2[j];
}
// 在合并后的字符串末尾添加null终止符
str1[i] = '\0';
printf("Merged string is: %s", str1);
return 0;
}
在上面的代码中,我们使用两个for循环来合并两个字符串。第一个循环用于找到第一个字符串的末尾,第二个循环将第二个字符串追加到第一个字符串的末尾。最后,我们在合并后的字符串末尾添加了一个null终止符。
原文地址: https://www.cveoy.top/t/topic/bkKS 著作权归作者所有。请勿转载和采集!