替换空格问题_萌新的日常的技术博客_51CTO博客
source link: https://blog.51cto.com/u_15787387/5780340
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
替换空格问题
精选 原创实现一个函数,将一个字符串的每个空格替换成"%20",例如,当字符串为 We Are Happy.则经过替换之后的字符串为 We%20Are%20Happy.
>#include<stdio.h>
#include<string.h>
void replaceSpace(char* str, int length)
{
int sum = 0;
char* cur = str;
while (*cur != '\0')
{
if (*cur == ' ')
{
sum++;
}
cur++;
}
char* end1 = str + length - 1;
char* end2 = str + length + 2 * sum - 1;
while (end1 != end2)
{
if (*end1 != ' ')
{
*end2-- = *end1--;
}
else
{
*end2-- = '0';
*end2-- = '2';
*end2-- = '%';
end1--;
}
}
}
int main()
{
char arr[40] = "We Are Happy";
int len = strlen(arr);
replaceSpace(arr, len);
printf("%s\n", arr);
return 0;
}
刚开始时,根据空格的个数,来决定向后要走几个2
如图,若有两个空格,则向后移4个单位
当end1指向空格时,此时需要将 % 2 0 分别逆置 即打印 0 2 %在end2所指向处,
如图一,刚开始end1处于空格处,end2处于p处,
当将三个字符打印完毕后, end1–,end2–,如图二,end1处于e处,end2处于H处
此时end1处于e处,因为不是空格,所以将所在的数据传递给end2处
如图一,当end1再次遇见空格时,end2处于r处,完成对于 % 2 0三个字符的逆置放入end2中
如图二,在完成逆置 后,end1-- ,end2-- ,此时end1与end2同时处于e处
两者处于同一个位置,将同时完成
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK