左旋字符串源码

#include <iostream>
using namespace std;

void Reverse( char *pBegin, char *pEnd )
{
	if( pBegin == NULL || pEnd == NULL )
		return;

	while( pBegin < pEnd )
	{
		char tmp = *pBegin;
		*pBegin = *pEnd;
		*pEnd = tmp;

		pBegin++, pEnd--;
	}
}

char *ReverseSentence( char *pData )
{
	if( pData == NULL )
		return NULL;

	char *pBegin = pData;
	char *pEnd = pData;
	while( *pEnd != '\0' )
		pEnd++;
	pEnd--;

	//反转整个句子
	Reverse( pBegin, pEnd );

	//反转句子中个每个单词
	pBegin = pEnd = pData;
	while( *pBegin != '\0' )
	{
		if( *pBegin == ' ' )
		{
			pBegin++;
			pEnd++;
		}
		else if( *pEnd == ' ' || *pEnd == '\0' )
		{
			Reverse( pBegin, --pEnd );
			pBegin = ++pEnd;
		}else
		{
			pEnd++;
		}
	}
	return pData;
}

void LeftReverse( char *pData, int n )
{
	if( pData == NULL )
		return;
	char *pBegin = pData;
	char *pEnd = pData;
	while( *pEnd != '\0' )
	{
		pEnd++;
	}
	pEnd--;

	int mid = (n % strlen(pData)) - 1;

	Reverse( pBegin, pBegin + mid );
	cout << "左旋反转1: " << pData << endl;
	Reverse( pBegin + mid + 1, pEnd );
	cout << "左旋反转2: " << pData << endl;
	Reverse( pBegin, pEnd ); //pData
	cout << "左旋反转3: " << pData << endl;

}

void Test( char *testName, char *input, char *expectedResult )
{
	if( testName != NULL)
		cout << testName << " begins: " << endl;

	if( input != NULL )
	{
		cout << "反转前:" << input << endl; 
		//ReverseSentence( input );
		LeftReverse( input, 2);  //翻转2个字符
		cout << "反转后:" << input << endl;  
	}

	if( (input == NULL && expectedResult == NULL)
		|| (input != NULL && strcmp(input, expectedResult) == 0) )
		cout << "通过!" << endl;
	else
		cout << "失败!" << endl;
}

void TestReverse()
{
	char input[] = "ABCDEFG";
	char expected[] = "CDEFGAB";

	Test( "Left Reverse", input, expected );
}

void TestReverse0()
{
	char input[] = "I am a student.";//这些字符串放置在堆栈中
    char expected[] = "student. a am I";
	
	Test( "One Sentence", input, expected );
	//以下会产生错误,这些字符串放置在.rdata段中,只读
	//Test( "One word", "I am a student.", "student. a am I" );
}

void TestReverse1()
{
	char input[] = "lfz";
	char expected[] = "lfz";
	
	Test( "One word", input, expected );
}

void TestReverse2()
{
	Test( "NULL", NULL, NULL );
}

void TestReverse3()
{
	char input[] = "";
	char expected[] = "";
	
	Test( "Empty", input, expected );
}

void TestReverse4()
{
	char input[] = " ";
	char expected[] = " ";
	
	Test( "One Blanks", input, expected );

}

void TestReverse5()
{
	char input[] = "   ";
	char expected[] = "   ";
	
	Test( "Three Blanks", input, expected );

}

void main()
{
	//
	TestReverse();
	//TestReverse0();
	//TestReverse1();
	//TestReverse2();
	//TestReverse3();
	//TestReverse4();
	//TestReverse5();

	system( "PAUSE");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值