这道题最重要的就是要意识到空格是占一个字符,而%20是占三个字符,所以涉及到了字符串长度的增加。
下面有四种方法:
#include<stdio.h>
#include<string.h>
void replace1(char *arr1, char *arr2)
{
while (*arr1)
{
if (*arr1 != ' ')
{
*arr2 = *arr1;
arr2++;
}
else
{
strcpy(arr2, "%20"); //将两个字符串连接
arr2 = arr2 + 3; //arr2指针移动到连接后的下一位
}
arr1++;
}
}
void replace2(char *p,int length)
{
while (*p != '\0')
{
char *pc = p + length;
while (*p != ' ')
{
p++;
if (*p == '\0') //避免指针越界,非法访问,导致崩溃
{
return; //退出函数
}
}
while (pc != p)
{
*(pc + 2) = *(pc);
pc--;
}
*p = '%';
*(p + 1) = '2';
*(p + 2) = '0';
p += 3;
}
}
int main(){
char str[50];
int i=0;
int count=0,NewSize=0;
printf("please input string:\n");
// gets(str);
char arr1[50],arr2[50];
gets(arr1);
int length;
length=sizeof(arr1)/sizeof(arr1[0]);//也可以这样求长度
//双指针实现 这里的指针并不是指C语言指向地址的指针
// int x=strlen(str);
// for (int i = 0; i < x; i++) {
// if (str[i] == ' ') count++;
// }
// NewSize=x+count*2;
// for (int i = NewSize - 1, j = x - 1; j < i; i--, j--) {
// if (str[j] != ' ') {
// str[i] = str[j];
// } else {
// str[i] = '0';
// str[i - 1] = '2';
// str[i - 2] = '%';
// i -= 2;
// }
// }
//真正的指针
int l=strlen(arr1);
char *p;
for(p=arr1;p<(arr1+l);p++){
if(*p==' ') count++;
}
NewSize=l+count*2;
char *s , *j;
s = &arr1[NewSize - 1];
j = &arr1[l - 1];
for ( ;j < s; s--, j--) {
if (*j != ' ') {
*s = *j;
} else {
*s = '0';
*(s -1) = '2';
*(s -2) = '%';
s -= 2;
}
}
// replace1(arr1, arr2);
// replace2(arr1,length);
printf("%s",arr1);
}