请实现一个函数,把字符串的每个空格替换成“%20”。例如,输入“We are happy.”,则输出“We%20are%20happy”。
思路:
我们首先能够相到的是原来一个空格字符,替换之后变成‘%’、‘2’、‘0’这三个字符,因此字符串会变长。如果是在原来的字符串上进行替换,就有可能覆盖修改在该字符串后面的内存。如果是创建新的字符串并在新的字符串上进行替换,那么我们可以自己分配足够多的内存。
第一步:遍历字符串,统计空格的数目
第二步:根据原字符串长度和空格数目,创建新的数组(new_size=size+2*count)
第三步:创建两个指针,分别指向定义的新旧数组。然后开始复制、替换。
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
typedef enum status
{
InValid,
Valid,
}status;
status opion = InValid;
char *ReplaceBlank(char *str, int sz)
{
if (str == NULL)//空指针
return NULL;
if (*str == '\0')//空字符串
{
opion = InValid;
return NULL;
}
int count = 0;
int i = 0;
while (str[i])//找出空格数
{
if (str[i] == ' ')
count++;
i++;
}
opion = Valid;
char *new_str = (char *)malloc(sizeof(char)*(sz + 2 * count));
assert(new_str);
int OldIndex = 0, Newindex = 0;
while (OldIndex <= sz)
{
if (str[OldIndex] == ' ')
{
new_str[Newindex++] = '%';
new_str[Newindex++] = '2';
new_str[Newindex++] = '0';
}
else
new_str[Newindex++] = str[OldIndex];
OldIndex++;
}
return new_str;
}
int main()
{
char arr[] = "";
int sz = sizeof(arr) / sizeof(arr[0]);
char *p = ReplaceBlank(&arr, sz);
printf("%s\n", opion == InValid ? "不合法输入" : "合法输入");
printf("%s\n", p);
system("pause");
return 0;
}