左旋字符串源码

来源:互联网 发布:linux搭建测试环境 编辑:程序博客网 时间:2024/05/16 02:10
#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--;}}char *ReverseSentence( char *pData ){if( pData == NULL )return NULL;char *pBegin = pData;char *pEnd = pData;while( *pEnd != '\0' )pEnd++;pEnd--;//反转整个句子Reverse( pBegin, pEnd );//反转句子中个每个单词pBegin = pEnd = pData;while( *pBegin != '\0' ){if( *pBegin == ' ' ){pBegin++;pEnd++;}else if( *pEnd == ' ' || *pEnd == '\0' ){Reverse( pBegin, --pEnd );pBegin = ++pEnd;}else{pEnd++;}}return pData;}void LeftReverse( char *pData, int n ){if( pData == NULL )return;char *pBegin = pData;char *pEnd = pData;while( *pEnd != '\0' ){pEnd++;}pEnd--;int mid = (n % strlen(pData)) - 1;Reverse( pBegin, pBegin + mid );cout << "左旋反转1: " << pData << endl;Reverse( pBegin + mid + 1, pEnd );cout << "左旋反转2: " << pData << endl;Reverse( pBegin, pEnd ); //pDatacout << "左旋反转3: " << pData << endl;}void Test( char *testName, char *input, char *expectedResult ){if( testName != NULL)cout << testName << " begins: " << endl;if( input != NULL ){cout << "反转前:" << input << endl; //ReverseSentence( input );LeftReverse( input, 2);  //翻转2个字符cout << "反转后:" << input << endl;  }if( (input == NULL && expectedResult == NULL)|| (input != NULL && strcmp(input, expectedResult) == 0) )cout << "通过!" << endl;elsecout << "失败!" << endl;}void TestReverse(){char input[] = "ABCDEFG";char expected[] = "CDEFGAB";Test( "Left Reverse", input, expected );}void TestReverse0(){char input[] = "I am a student.";//这些字符串放置在堆栈中    char expected[] = "student. a am I";Test( "One Sentence", input, expected );//以下会产生错误,这些字符串放置在.rdata段中,只读//Test( "One word", "I am a student.", "student. a am I" );}void TestReverse1(){char input[] = "lfz";char expected[] = "lfz";Test( "One word", input, expected );}void TestReverse2(){Test( "NULL", NULL, NULL );}void TestReverse3(){char input[] = "";char expected[] = "";Test( "Empty", 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(){//TestReverse();//TestReverse0();//TestReverse1();//TestReverse2();//TestReverse3();//TestReverse4();//TestReverse5();system( "PAUSE");}

原创粉丝点击