字符串循环移动

编程珠玑2.3节中的字符串循环移动算法

字符串循环移动_第1张图片

自己写个代码以作记录

#include <iostream>
using namespace std;

void CycLeftMove(char szBuf[],int nLen,int nMovNum)
{
	char chTmp;
	for(int i = 0;i<nMovNum;i++)
	{
		chTmp = szBuf[i];
		for(int j= 1;;j++)
		{
			if(j*nMovNum >= nLen)
			{
				szBuf[(j-1)*nMovNum + i] = chTmp;
				break;
			}
			szBuf[(j-1)*nMovNum + i] = szBuf[i + j*nMovNum];
		}

	}

	cout<<nLen<<endl;
}

void CycRightMove(char szBuf[],int nLen,int nMovNum)
{
	char chTmp;
	for(int i=0;i<nMovNum;i++)
	{
		chTmp = szBuf[nLen -nMovNum + i];
		for(int j = 0;;j++)
		{
			if(nLen -nMovNum + i -j*nMovNum < nMovNum)
			{
				szBuf[nLen-nMovNum +i - nMovNum*j] = chTmp;
				break;
			}
			szBuf[nLen-nMovNum +i - nMovNum*j] = szBuf[nLen-nMovNum +i - nMovNum*(j+1)];
		}

	}
}


int main()
{
	char buf[]="abcdefghijkl";
//	CycLeftMove(buf,sizeof(buf)-1,3);
	CycRightMove(buf,sizeof(buf)-1,3);
	cout<<buf<<endl;
	return 0;
}


你可能感兴趣的:(字符串循环移动)