剑指 2.替换空格

链接

题目

在这里插入图片描述

思路

字符串有足够的空余内存
先统计空格的个数
替换后的长度 = 原长度 + 空格长度 * 2
从尾部到头部开始移动

源码

class Solution {
public:
	void replaceSpace(char *str,int length) {
        int spacenum = 0, len = strlen(str);
        for (int i = len - 1; i >= 0; i--) {
            if (str[i] == ' ') spacenum++;
        }
        int i = len, j = len + spacenum * 2;
        for (int i = len; i >= 0; i--) {
            if (str[i] == ' ') {
                str[j--] = '0';
                str[j--] = '2';
                str[j--] = '%';
            } else {
                str[j--] = str[i];
            }
        }
        return ;
	}
};

其他

char s1 = "hello world";
char s2 = "hello world";
char *s3 = "hello world";
char *s4 = "hello world";
if (str1 == str2) printf("s1 and s2 are same\n");
else printf("s1 and s2 are not same\n");

if (str3 == str4) printf("s3 and s4 are same\n");
else printf("s3 and s4 are not same\n");

输出的是 s1 and s2 are not sames3 and s4 are same;
s1 和 s2 是两个数组初始地址不同
s3 和 s4 是两个指针,都指向 "hello world"这个常量字符串所在的内存地址。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值