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

2014-11-24 02:42:12 · 作者: · 浏览: 1

将字符串字符顺序反转:

[cpp]
#include
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");
}