將字符串字符順序反轉:
[cpp]
#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");
}