#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxn 512
int main() {
char s[maxn] = { 0 };
char *p;
int i=0,j=0,count = 0;
while (gets(s) != NULL) {
count = 0,i=0;
while (s[i]) {
if (s[i] == ' ') {
count++;
}
i++;
}
p = (char *)calloc(1, strlen(s) + 3 * count + 1);
for (i = strlen(s) - 1, j = strlen(s) + 3 * count - 1; i >= 0; i--) {
if (s[i] == ' ') {
p[j] = '0';
p[j - 1] = '2';
p[j - 2] = '0';
p[j - 3] = '%';
j = j - 4;
}
else {
p[j] = s[i];
j--;
}
}
printf("%s\n", p);
free(p);
p = NULL;
}
return 0;
}
Notes:
j = strlen(s) + 3 * count - 1
假设你字符串长度是30,你申请了31字符的空间,你最后一个字母的位置是s[29],肯定不是s[30]. s[30]是结束符。数组下标是从0开始的。