|
/***
*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 由于要交換數(shù)據(jù), 所以會有變化
char *start = string;
char *left = string;
char ch;
while (*string++) /* find end of string */
;
string -= 2; // 指針后退2, 得到最后一個字符的指針地址.
// 此段邏輯就是 前后字符交換, 比如 "abcde":
// 第一次循環(huán), a 和 e 交換后 變成ebcda,
// 第二次循環(huán)b和d交換, 變成edcba,
// 第三次由于left==string, 故循環(huán)停止.
while (left < string)
{
ch = *left;
*left++ = *string; // 此處可分解為兩步更好理解: *left =*sting; left++; 把值付給*left, 然后left向后移位
*string-- = ch; // 同上: *string = ch; string--; 把值付給*string, 然后string向前移位
}
return(start);
}
另外一種利用strlen函數(shù)來得到字符串長度的方法, 其原理跟上面的相同: 首尾依次交換到中間為止.
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;
}
|