字符串处理 | reverse_copy

题目描述:

写C语言的拷贝函数,要求复制字符串,并且将复制后的字符串逆序
  比如form中是1234, 则to中是4321
  void reverse_copy(char * to,const char * form)
  不能使用库函数 不能定义其他的变量

不能定义其他变量,也不能用库,就只能用利用栈空间了,代码如下:

 1 /* reverse_copy without null */
 2 char *reverse_copy_noend(char *to, char *from)
 3 {
 4     if(*from == '\0') return to;
 5 
 6     to = reverse_copy_noend(to, from+1);
 7     *to = *from;
 8 
 9     return ++to;
10 }
11 
12 void reverse_copy(char *to, char *from)
13 {
14     if(to == 0 || from == 0) return;
15 
16     to = reverse_copy_noend(to, from);
17     *to = '\0';
18 }

 

抛去限制的话:

 

 1 void reverse_copy(char *to, char *from)
 2 {
 3     if(to == 0 || from == 0) return;
 4 //    to = reverse_copy_noend(to, from);
 5 //    *to = '\0';
 6     //register
 7     char *from_end = from + strlen(from);   // 通常会给 from_end
 8 
 9     do {
10         *to++ = *from_end;
11     } while(from_end-- != from);
12 }
View Code

 

posted on 2015-10-09 13:27  Excavator  阅读(299)  评论(0编辑  收藏  举报

导航