#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的源代码及测试用例
最新推荐文章于 2019-01-13 20:06:45 发布