题目
思路
字符串有足够的空余内存
先统计空格的个数
替换后的长度 = 原长度 + 空格长度 * 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 same
和 s3 and s4 are same
;
s1 和 s2 是两个数组初始地址不同
s3 和 s4 是两个指针,都指向 "hello world"这个常量字符串所在的内存地址。