字串替換空格:請實現一個函式,把字元陣列中的每個空格替換成“%20”
阿新 • • 發佈:2019-02-14
例如輸入“we are happy”,則輸出“we%20are%20happy”
想要實現這個目的,先觀察下面的函式實現原理圖。
先通過遍歷字元陣列,找出其中的空格數,計算出應該移動到的位置,接著就是移動指標,並在遇到空格時插入%20,函式便可實現。
具體實現程式碼如下:
#include <stdio.h>
char replace(char* src)
{
int count = 0;
char *end = NULL;
char *pend = NULL;
char *str = src;
while (*str)
{
if (*str == ' ')
{
count++;
}
str++;
}
end = str - 1;
pend = end + 2 * count;
while (end != pend)
{
if (*end != ' ')
{
*pend-- = *end--;
}
else
{
*pend-- = '0';
*pend-- = '2' ;
*pend-- = '%';
end--;
}
}
printf("%s\n", src);
}
int main()
{
char src[30] = "we are happy.";
replace(src);
system("pause");
return 0;
}