#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class Solution {
public:
void replaceSpace(char *str,int length) {
if (str == nullptr || length < 0){
return;
}
int blank = 0;
int ori_len = 0;
for(int i = 0; str[i] != '\0'; i++){
++ ori_len;
if(str[i] == ' '){
blank++;
}
}
int newlength = ori_len + 2*blank;
if (newlength > length){
return;
}
int i_ori = ori_len;
int i_new = newlength;
while(i_ori >= 0 && i_new > i_ori){
if(str[i_ori] == ' '){
str[i_new--] = '0';
str[i_new--] = '2';
str[i_new--] = '%';
}
else{
str[i_new--] = str[i_ori];
}
-- i_ori;
}
cout << str << endl;
}
};
int main()
{
Solution s;
char str[] = "we are happy.";
cout << str << endl;
s.replaceSpace(str, 20);
return 0;
}
这里有一点要注意的,我一开始在main函数里面写的是
char *str = "we are happy.";
这样子程序会报错,猜测因为char* 方式定义的字符串是存放在编译器常量区,不能改动。
char [] 方式定义是放栈中,可改动。