新手发帖,很多方面都是刚入门,有错误的地方请大家见谅,欢迎批评指正
将字符串字符序顺反转:
#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,微软笑了;微软说我的系统很稳定,我们都笑了。