一、題目
輸入一個英文句子,翻轉句子中單詞的順序,但單詞内字元的順序不變。為簡單起見,标點符号和普通字母一樣處理。例如輸入字元串"I am a student. ",則輸出"student. a am I"。
二、關鍵
1.反轉兩次。第一次:“.tneduts a ma i”,第二次,每個單詞反轉:“student. a am i”
2.反轉字元串的一段的函數reverse。
三、解釋
四、代碼
#include <cstdio>
#include "..\Utilities\StringUtil.h"
#include <string>
void Reverse(char*pBegin, char* pEnd)
{
if(pBegin==nullptr||pEnd == nullptr)
return ;
while(pBegin<pEnd)
{
char temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
pBegin++,pEnd++;
}
}
char* ReverseSentence(char *pData)
{
if(pData == nullptr)
return nullptr;
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 Test(const char* testName, char* input, const char* expectedResult)
{
if(testName != nullptr)
printf("%s begins: ", testName);
ReverseSentence(input);
if((input == nullptr && expectedResult == nullptr)
|| (input != nullptr && strcmp(input, expectedResult) == 0))
printf("Passed.\n\n");
else
printf("Failed.\n\n");
}
// 功能測試,句子中有多個單詞
void Test1()
{
char input[] = "I am a student.";
char expected[] = "student. a am I";
Test("Test1", input, expected);
}
// 功能測試,句子中隻有一個單詞
void Test2()
{
char input[] = "Wonderful";
char expected[] = "Wonderful";
Test("Test2", input, expected);
}
// 魯棒性測試
void Test3()
{
Test("Test3", nullptr, nullptr);
}
// 邊界值測試,測試空字元串
void Test4()
{
Test("Test4", "", "");
}
// 邊界值測試,字元串中隻有空格
void Test5()
{
char input[] = " ";
char expected[] = " ";
Test("Test5", input, expected);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
return 0;
}