1.思路:
1>重新定义一个新的数组,并进行赋值
2>确定变换后数组的长度,再从后往前更新数组,记得在最开始要先加’\0’
2.代码:
方案一:
class Solution {
public:
void replaceSpace(char *str,int length) {
char* tmp = (char*)malloc(sizeof(char) * length);
for(int k = 0; k < length; ++k){
tmp[k] = str[k];
}
int i, j = 0;
for (i = 0; i < length ; ++i){
if(tmp[i] == ' '){
str[j++] = '%';
str[j++] = '2';
str[j++] = '0';
} else {
str[j++] = tmp[i];
}
} //赋值的最后一个是'\0',即字符串结束符
}
};
方案二:
class Solution {
public:
void replaceSpace(char *str,int length) {
int strlen = 0, spacenum = 0;
for(int i = 0; i < length; ++i){
if(str[i] == '\0') break;
if(str[i] == ' '){
spacenum++;
}
strlen++;
}
int newstrlen = strlen + spacenum * 2;
int j = newstrlen;
if(newstrlen > length)
return;
str[j--] = '\0';
for(int i = strlen-1; i >= 0; --i){
if(str[i] != ' '){
str[j--] = str[i];
} else {
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
}
}
}
};
3.小结:
方案一:指针型数组若进行整体赋值操作,如char* tmp = str,那么在对tmp进行赋值运算时,str内的数值也会改变,因此要对tmp数组用malloc重新分配地址,然后进行逐个赋值,使其拥有相同的数据而对应不同的地址,malloc完使用delete删除申请的堆空间。
方案二:char c[ ]=”C program”;
注意:此时数组c的长度不是9,而是10。因为字符串常量的最后由系统加上一个’\0’。上面的初始化与下面的初始化等价。
char c[ ]={‘c’,‘ ’,‘p’,‘r’,‘o’,’g’,’r’,’a’,’m’,’\0’}。当给定的空间大于实际空间时,字符数组内无存储内容,但存在存储空间,例如:【c’,‘ ’,‘p’,‘r’,’\0’, , , 】