不常用指针,总是感觉别扭。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
class Solution {
public:
void replaceSpace(char *str,int length) {
int cnt = 0;
char ch;
for(int i = 0; i < length; i++) {
ch = *(str+i);
if(ch == ' ') cnt++;
}
char *s,*st = (char*)malloc((length+4*cnt)*sizeof(char));
s = st;
for(int i = 0; i < length; i++) {
ch = *(str+i);
if(ch == ' ') {
*st = '%';
st++;
*st = '2';
st++;
*st = '0';
st++;
}
else {
*st = ch;
st++;
}
}
cnt = st-s;
for(int i = 0; i < cnt; i++) {
*(str+i) = *(s+i);
}
*(str+cnt) = '\0';
}
};
/** 可以运行主函数来测试。
int main() {
char a[100];
while(gets(a)) {
Solution s;
s.replaceSpace(a,strlen(a));
puts(a);
}
return 0;
}**/