#include "stdio.h"
/*length 为字符数组string的总容量*/
void ReplaceBlank(char string[], int length)
{
if(string == NULL || length <= 0)
return;
int original_Length = 0; //字符串string的实际长度
int number_Of_Blank = 0; //空格数量
for(int i=0;string[i] != '\0';i++)
{
++ original_Length;
if(string[i] == ' ')
++ number_Of_Blank;
}
/*newLength 为把空格替换成'%20'之后的长度*/
int new_Length = original_Length + number_Of_Blank * 2;
if(new_Length > length)
return;
int index_Of_Original = original_Length;
int index_Of_New = new_Length;
while(index_Of_Original >= 0 && index_Of_New > index_Of_Original)
{
if(string[index_Of_Original] == ' ')
{
string[index_Of_New --] = '0';
string[index_Of_New --] = '2';
string[index_Of_New --] = '%';
}
else
string[index_Of_New --] = string[index_Of_Original];
-- index_Of_Original;
}
}
int main()
{
char str[30]="we are happy.";
ReplaceBlank(str,30);
printf("%s\n",str);
return 0;
}
剑指offer--面试题5:替换空格
最新推荐文章于 2021-04-12 23:45:40 发布