左文字列ソース


#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 ); //pData
	cout << "    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;
	else
		cout << "  !" << 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");
}