题目描述C语言每日一练
2021年10月2日
连接两个字符串
分析简单实现strcat库函数
代码实现#include#define MEMORY_PROTECTION 1 //是否开启内存保护 #define LEN_STRING 20 //字符串空间大小 char *my_strcat(char *str1, const char *str2); int main() { char str1[LEN_STRING]; char str2[LEN_STRING]; int len1 = 0; int len2 = 0; printf("请输入两个字符串n"); scanf("%s%s", str1, str2); while(str1[len1] != ' ') len1++; while(str2[len2] != ' ') len2++; #if MEMORY_PROTECTION //内存保护 if(LEN_STRING < len1 + len2) { printf("字符串1空间不足,无法连接!n"); return 1; } #endif my_strcat(str1, str2); printf("字符串连接后:n"); printf("%sn", str1); return 0; } char *my_strcat(char *str1, const char *str2) { while(*str1 != ' ')// 同*str != NULL? { str1++; } while(*str2 != ' ') { *str1++ = *str2++; } *str1 = ' '; return str1; }
运行结果



