Life is Good.

Enhance Tech and English
随笔 - 65, 文章 - 20, 评论 - 21, 引用 - 0
数据加载中……

1 - strrev

/***
*strrev.c - reverse a string in place
*
*       Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved.
*
*Purpose:
*       defines _strrev() - reverse a string in place (not including
*       '\0' character)
*
******************************************************************************
*/

#include 
<cruntime.h>
#include 
<string.h>

/***
*char *_strrev(string) - reverse a string in place
*
*Purpose:
*       Reverses the order of characters in the string.  The terminating
*       null character remains in place.
*
*Entry:
*       char *string - string to reverse
*
*Exit:
*       returns string - now with reversed characters
*
*Exceptions:
*
******************************************************************************
*/

char * __cdecl _strrev (char * string)
{
        
// 此段程序的start/left/string 都在同一块内存中, start记录的是起始地址,未变动过
        
// left和string 由于要交换数据, 所以会有变化
        char *start = string;
        
char *left = string;
        
char ch;

        
while (*string++)                 /* find end of string */
                ;
        
string -= 2// 指针后退2, 得到最后一个字符的指针地址.

        
// 此段逻辑就是 前后字符交换, 比如 "abcde":
        
// 第一次循环, a 和 e 交换后 变成ebcda, 
        
// 第二次循环b和d交换, 变成edcba,
        
// 第三次由于left==string, 故循环停止.
        while (left < string)
        {
                ch 
= *left; 
                
*left++ = *string// 此处可分解为两步更好理解: *left =*sting; left++; 把值付给*left, 然后left向后移位
                *string-- = ch;      // 同上: *string = ch; string--; 把值付给*string, 然后string向前移位
        }

        
return(start);
}


另外一种利用strlen函数来得到字符串长度的方法, 其原理跟上面的相同: 首尾依次交换到中间为止.
char* my_strrev(char* p)
{
  
int n = strlen(p);
  
int i = 0;
  
int j = 0;
  
char ch;

  
for (i = 0, j = n-1; i < j; i++, j--)
  {
    ch 
= p[i];
    p[i] 
= p[j];
    p[j]
=ch;
  }

  
return p;
}

int _tmain(int argc, _TCHAR* argv[])
{
  
// 此处不能定义为char* p = "abcde";
  
// 因为在strrev里面要修改p的内容.
  char p[] = "abcde"
  
char* p1 = strrev(p);
  
char* p2 = my_strrev(p);

  
return 0;
}

posted on 2011-06-01 23:12 Mike Song 阅读(361) 评论(0)  编辑 收藏 引用 所属分类: C字符串函数源码分析


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理