#include <iostream>
#include <assert.h>
void ReplaceBlank(char string[],int capacity)//capacity爲數組str的總容量
{
if (string == NULL || capacity <= 0)
return;
int length = 0;
int blank_count = 0;
int i = 0;
while (string[i]!='\0')
{
length++;
if (string[i] == ' ')
{
blank_count++;
}
i++;
}
int newLength = length + blank_count * 2;
if (newLength > capacity)
return;
int indexOld = length;
int indexNew = newLength;
while (indexOld >= 0 && indexNew >= indexOld)
{
if (string[indexOld] == ' ')
{
string[indexNew--] = '0';
string[indexNew--] = '2';
string[indexNew--] = '%';
}
else
{
string[indexNew] = string[indexOld];
indexNew--;
}
--indexOld;
}
}
void Test(char* testName, char string[], int length, char expected[])
{
if (testName != NULL)
printf("%s begins: ", testName);
ReplaceBlank(string, length);
if (expected == NULL && string == NULL)
printf("passed.\n");
else if (expected == NULL && string != NULL)
printf("failed.\n");
else if (strcmp(string, expected) == 0)
printf("passed.\n");
else
printf("failed.\n");
}
// 空格在句子中間
void Test1()
{
const int length = 100;
char string[length] = "hello world";
Test("Test1", string, length, "hello%20world");
}
// 空格在句子開頭
void Test2()
{
const int length = 100;
char string[length] = " helloworld";
Test("Test2", string, length, "%20helloworld");
}
// 空格在句子末尾
void Test3()
{
const int length = 100;
char string[length] = "helloworld ";
Test("Test3", string, length, "helloworld%20");
}
// 連續有兩個空格
void Test4()
{
const int length = 100;
char string[length] = "hello world";
Test("Test4", string, length, "hello%20%20world");
}
// 傳入NULL
void Test5()
{
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] = "helloworld";
Test("Test8", string, length, "helloworld");
}
// 傳入的字符串全是空格
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();
return 0;
}
將一個字符串中的所有空格替換爲%20的源代碼及測試用例
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.