/*
版本1:
将空格后面的元素后移,然后在将空格替换为%20。
缺点:
时间复杂度为O(n^2)
*/
char* ReplaceBlank1(char string[])
{
if (string != NULL)
{
int index = 0;
while (string[index] != '\0')
{
//遇到空格进行替换
if (' ' == string[index])
{
int i = strlen(string);
//将空格后面的元素进行后移
for (i; i > index; i--)
{
string[i + 2] = string[i];
}
string[index] = '%';
string[++index] = '2';
string[++index] = '0';
}
index++;
}
}
return string;
}
/*
版本2:
用两个指针从字符串末尾从前进行遍历。
需要先得到字符串长度和替换之后字符串的长度。
时间复杂度:O(n)
we are happy.
*/
char* ReplaceBlank2(char arr[], int length)//length为字符串的strlen()结果
{
if (NULL == arr || length <= 0)
return NULL;
int startStrLength = 0;//开始时字符串的长度(strlen()结果)
int endStrLength = 0;//替换结束时字符串的长度(strlen()结果)
int i = 0;
int count = 0;
while ('\0' != arr[i])
{
if (' ' == arr[i])
count++;
i++;
}
//在进行替换之后字符串会变长,为了防止字符被覆盖,所以从后向前进行
startStrLength = length;//指向最后一个字符'\0'
endStrLength = startStrLength + count * 2;//指向替换结束最后一个字符
while (startStrLength >= 0 && endStrLength >= 0)
{
if (' ' != arr[startStrLength])
{
//字符转移
arr[endStrLength] = arr[startStrLength];
}
else
{
//空格替换
arr[endStrLength] = '0';
arr[--endStrLength] = '2';
arr[--endStrLength] = '%';
}
//向前移动
startStrLength--,endStrLength--;
}
return arr;
}
字符串替换空格: 请实现一个函数,把字符数组中的每个空格替换成“%20”。 例如输入“we are happy.”,则输出“we are happy.”
最新推荐文章于 2022-04-02 17:07:23 发布