题目:请实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“We are happy.”,则输出“We%20are%20happy.”。
解析:时间复杂度为O(n)的解法。
完整代码及测试用例实现:
#include<iostream>
using namespace std;
#include <cstring>
//length 为字符数组string的总容量
void ReplaceBlank(char string[], int length)
{
if (string == NULL&&length <= 0)
{
return;
}
//reallyLength 为字符串string的实际长度
int reallyLength = 0, numberOfBlank = 0,i=0;
while (string[i]!='\0')
{
++reallyLength;
if (string[i] == ' ')
{
++numberOfBlank;
}
++i;
}
//newLength 为把空格替换成'%20'之后的长度
int newLength = reallyLength + numberOfBlank * 2;
if (newLength > length)
{
return;
}
int indexOfReally = reallyLength;
int indexOfNew = newLength;
while (indexOfReally >= 0 && indexOfNew >indexOfReally)
{
if (string[indexOfReally] == ' ')
{
string[indexOfNew--] = '0';
string[indexOfNew--] = '2';
string[indexOfNew--] = '%';
}
else
{
string[indexOfNew--] = string[indexOfReally];
}
--indexOfReally;
}
}
// ====================测试代码====================
void Test(char* testName, char string[], int length, char expected[])
{
if (testName != NULL)
{
cout << testName << " begins: ";
}
ReplaceBlank(string, length);
if (expected == NULL && string == NULL)
{
cout << "passed." << endl;
}
else if (expected == NULL && string != NULL)
{
cout << "failed." << endl;
}
else if (strcmp(string, expected) == 0)
{
cout << "passed." << endl;
}
else
{
cout << "failed." << endl;
}
}
void Test1()
{
// 空格在句子中间
const int length = 100;
char string[length] = "we are happy.";
Test("Test1", string, length, "we%20are%20happy.");
}
void Test2()
{
// 空格在句子开头
const int length = 100;
char string[length] = " wearehappy.";
Test("Test2", string, length, "%20wearehappy.");
}
void Test3()
{
// 空格在句子末尾
const int length = 100;
char string[length] = "wearehappy. ";
Test("Test3", string, length, "wearehappy.%20");
}
void Test4()
{
// 连续有两个空格
const int length = 100;
char string[length] = "we are happy.";
Test("Test4", string, length, "we%20%20are%20happy.");
}
void Test5()
{
// 传入NULL
Test("Test5", NULL, 0, NULL);
}
void Test6()
{
// 传入内容为空的字符串
const int length = 100;
char string[length] = "";
Test("Test6", string, length, "");
}
void Test7()
{
//传入内容为一个空格的字符串
const int length = 100;
char string[length] = " ";
Test("Test7", string, length, "%20");
}
void Test8()
{
// 传入的字符串没有空格
const int length = 100;
char string[length] = "wearehappy.";
Test("Test8", string, length, "wearehappy.");
}
void Test9()
{
// 传入的字符串全是空格
const int length = 100;
char string[length] = " ";
Test("Test9", string, length, "%20%20%20");
}
int main()
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
system("pause");
return 0;
}
运行结果:
Test1 begins: passed.
Test2 begins: passed.
Test3 begins: passed.
Test4 begins: passed.
Test5 begins: passed.
Test6 begins: passed.
Test7 begins: passed.
Test8 begins: passed.
Test9 begins: passed.
请按任意键继续. . .