替换空格
题目:实现一个函数,把字符串中的每个空格替换成%20,例如:输入"hello world!",输出"hellp%20world!"
- C语言实现:
void ReplaceBlank(char str[], int length)
{
int len = length;
int i = 0;
int NumberBlank = 0;
if (length <= 0 || str == NULL)
return;
for (; i < len; i++) //求空格个数
{
if (str[i] == ' ')
NumberBlank++;
}
int Newlength = length + NumberBlank * 2; //新字符串长度
int IndexOfOrigina = length - 1; //原末尾
int IndexOfNew = Newlength - 1; //新末尾
while (IndexOfOrigina > 0 && IndexOfNew > IndexOfOrigina)
{
if (str[IndexOfOrigina] == ' ') //处理空格
{
str[IndexOfNew--] = '0';
str[IndexOfNew--] = '2';
str[IndexOfNew--] = '%';
}
else
{
str[IndexOfNew--] = str[IndexOfOrigina];
}
IndexOfOrigina--;
}
}
int main()
{
char str[32] = "How are you";
int length = strlen(str) + 1;
int i = 0;
int j = 0;
for (; i < length; i++)
printf("%c", str[i]);
printf("\n");
ReplaceBlank(str, length);
int Newlength = sizeof(str);
for (; j < Newlength; j++)
printf("%c", str[j]);
printf("\n");
system("pause");
return 0;
}
运行代码:
- C++实现:
class Solution {
public:
void replaceSpace(char *str,int length)
{
if(length <= 0 || str == NULL)
return;
int count = 0;
for(int i = 0;i<length;i++) //计算空格数
{
if(str[i] == ' ')
++count;
}
int NewLength = length + count*2; //注意空格数要乘2
int Origina = length -1; //数组元素下标-1
int New = NewLength -1;
while(New >= Origina && Origina >= 0)
{
if(str[Origina] == ' ') //替换空格
{
str[New--] = '0';
str[New--] = '2';
str[New--] = '%';
Origina--;
}
else
str[New--] = str[Origina--];
}
}
};