剑指offer 替换空格

#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 [] 方式定义是放栈中,可改动。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值