strcpy Empty String Handling in C
The strcpy function in C language is used to copy one string to another. If the source string is empty, the target string will be set to empty directly. Below is an example code for handling the case where the source string is empty:
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "";
char dest[100];
if (strlen(src) == 0) {
dest[0] = '\0'; // 直接将目标字符串置空
} else {
strcpy(dest, src);
}
printf("目标字符串: %s\n", dest);
return 0;
}
In the code above, we first check if the source string src is empty. If it is empty, we directly set the first character of the destination string dest to ‘\0’ (null character). If the source string is not empty, we use the strcpy function to copy the source string to the destination string. Finally, we output the content of the destination string.