// 007.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
//全部翻转
bool AllReverse(char *pBegin, char *pEnd);
bool Reverse(char *pBuffer)
{
if (NULL == pBuffer)
{
return false;
}
char *pBegin = pBuffer;
int len =0;
while(*pBegin != '\0')
{
len++;
pBegin++;
}
char *pEnd = pBuffer+len-1;
bool bRet = false;//反转成功与否
pBegin = pBuffer;
bRet = AllReverse(pBegin, pEnd);
if (!bRet)
{
return false;
}
pBegin = pEnd = pBuffer;
//以空格为界限翻转每个字符串
char spaceChar = ' ';
while (*pBegin != '\0')
{
if (*pBegin == spaceChar)
{
pBegin++;
pEnd++;
continue;
}
else if (*pEnd == spaceChar || *pEnd == '\0')
{
AllReverse(pBegin, --pEnd);
pBegin = ++pEnd;//因为之前--pEnd,最终的位置指向了结束符或者空格符前一个字符
}
else
{
pEnd++;
}
}
}
bool AllReverse(char *pBegin, char *pEnd)
{
if (NULL == pBegin || NULL == pEnd)
{
return false;
}
//全部翻转
while(pBegin < pEnd)//不能为!=条件
{
char tmp = *pBegin;
*pBegin = *pEnd;
*pEnd = tmp;
pBegin++;
pEnd--;
}
return true;
}
//翻转字符串,先总体翻转再单个翻转
int main(int argc, char* argv[])
{
char pBuffer[] = "I AM A STUDENT.";
Reverse(pBuffer);
printf("%s", pBuffer);
return 0;
}
007字符串之一
最新推荐文章于 2023-03-17 12:37:51 发布