标签:c语言面试题 替换空格
题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入
"We are happy.",则输出"We%20are%20happy."。
思路:我们从字符串的后面复制和替换。首先准备两个指针,p1和p2。p1指向原字符串的末尾,p2指向替换之后的字符串的末尾。然后我们向前移动p1指针,逐个把它指向的字符复制到p2指向的位置,碰到空格就替换为"%20"。
代码如下:
#include <stdio.h>
void ReplaceBlank(char *s)
{
char *t;
char *tmp = s;
int count = 0; //总字符数(包括空格)
int blank = 0; //空格数
int i = 0;
if(*s == NULL)
return;
while(*tmp != ‘\0‘)
{
count++;
if(*tmp == ‘ ‘)
blank++;
tmp++;
}
tmp--;
t = tmp; //保留原字符串末尾
//We are happy.
//替换空格后字符串总字符数为count = count + 2*blank
count += blank<<1;
//让tmp指向替换空格后字符串的末尾
while(i<blank<<1)
{
tmp++;
i++;
}
tmp++;
*tmp = ‘\0‘;
tmp--;
//从后往前依次替换
while(*t)
{
if(*t == ‘ ‘)
{
*tmp-- = ‘0‘;
*tmp-- = ‘2‘;
*tmp-- = ‘%‘;
t--;
}
else
*tmp-- = *t--;
}
}
void print(char *s)
{
char *tmp = s;
while(*tmp != ‘\0‘)
{
printf("%c",*tmp);
tmp++;
}
printf("\n");
}
int main()
{
char c;
char s[100];
int i = 0;
printf("请输入一个字符串:\n");
scanf("%c",&c);
while(c != ‘\n‘)
{
s[i++] = c;
scanf("%c",&c);
}
s[i] = ‘\0‘;
ReplaceBlank(s);
print(s);
return 0;
}标签:c语言面试题 替换空格
原文地址:http://7876369.blog.51cto.com/7866369/1554784