在此我也给出一种结合逗号表达式和for循环语句来实现的参考代码:
#include <stdio.h>
void copy_string(char *from,char *to) { int i=0; for(;*to=*from,*from!='\0';from++,to++); return ; }
int main() { char str[]="this is a string!"; printf("%s\n",str); char dec_str[206]; copy_string(str,dec_str); printf("%s\n",dec_str); return 0; } |
运行结果为:
代码的巧妙之处在于结合了逗号表达式和for循环语句来实现,因为逗号表达式的结果为最后一个表达式的结果,所以执行判断语句里边的逗号表达式时其所取的值依然为*from!='\0'。
有兴趣的读者自己可以尝试下其他的实现方法,下面再给出几种很巧妙的实现方法,有兴趣的读者可以自己研究下其实现原理,均为完整代码。
#include <stdio.h>
void copy_string(char *from,char *to) { int i=0; for(;*to++=*from++;); return ; }
int main() { char str[]="this is a string!"; printf("%s\n",str); char dec_str[206]; copy_string(str,dec_str); printf("%s\n",dec_str); return 0; }
#include <stdio.h>
void copy_string(char *from,char *to) { int i=0; while(*to++=*from++); return ; }
int main() { char str[]="this is a string!"; printf("%s\n",str); char dec_str[206]; copy_string(str,dec_str); printf("%s\n",dec_str); return 0; } |