反转指向字符串反转C++实现源码(带测试用例)

新手发帖,很多方面都是刚入门,有错误的地方请大家见谅,欢迎批评指正

    将字符串字符序顺反转:

    

    每日一道理
无知者为梦想中的虚幻而苦苦等待,换回的不是所求的,而是岁月在脸上留下的印痕,一事无成的人一生便是虚度。生活中,与其花时间去等待,不如加快步伐去追寻理想,试着与时间赛跑,也许身躯、心理会感到劳累,但这样的生活毕竟是充实的。
#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--;
	}
}

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

	if( input == NULL )
		return;

	char *pBegin = input;

	char *pEnd = input; //临时
	while( *pEnd != '\0' )
		pEnd++;
	//pEnd此时经已指向'\0'了,退一个,指向最后一个字母
	pEnd--;
	//另外一种方法失掉pEnd
	//pEnd = pEnd + strlen(input) - 1;

	cout << "反转前:" << input << endl;
	Reverse( pBegin, pEnd );
	cout << "反转后:" << input << endl;

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

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

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

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

}

void TestReverse3()
{
	char input[] = "i am a student.";
	char expected[] = ".tneduts a ma i";
	
	Test( "A sentence", 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()
{
	//
	TestReverse0();
	TestReverse1();
	TestReverse2();
	TestReverse3();
	TestReverse4();
	TestReverse5();

	system( "PAUSE");
}

    考参了《剑指Offer》中的现实。

文章结束给大家分享下程序员的一些笑话语录: Borland说我很有前途,Sun笑了;Sun说我很有钱,IBM笑了;IBM说我很专业,Sybase笑了;Sybase说我数据库很牛,Oracle笑了;Oracle说我是开放的,Linux笑了;Linux说我要打败Unix,微软笑了;微软说我的系统很稳定,我们都笑了。

posted @ 2013-04-26 19:07  坚固66  阅读(284)  评论(0编辑  收藏  举报