您的位置:首页 > 其它

4--替换空格

2015-09-27 18:52 218 查看
/*
题目要求:
替换空格。
we are happy。
we%20are%20happy。

算法解析:
字符串长度为14.
先计算有多少个空格,测试字符串为2个。这样总长度为18.
从最后一个字符向后移动,注意控制指针,空格是1个字符,%20是三个。

*/

#include <stdio.h>

void replaceStr(char str[])
{
int count_space = 0;
int str_length = 0;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == ' ')
count_space++;
str_length++;
}
//    printf("%d\n",count_space);

int p1 = str_length;
int p2 = str_length + count_space * 2;
printf("%d, %d\n", p1, p2);

while (p1 != p2 || p1 < 0)
{
while (str[p1] != ' ')
{
str[p2--] = str[p1--];
}

str[p2--] = '0';
str[p2--] = '2';
str[p2--] = '%';

p1--;
}

}

int main()
{
char str[30] = "we are happy.";
replaceStr(str);

printf("%s\n", str);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: