您的位置:首页 > 编程语言 > C语言/C++

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

2013-04-26 09:37 621 查看
将字符串字符顺序反转:

#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》中的实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: