【刷一刷剑指Offer -- C++】 题目二 -- 替换字符串空格

/*
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
*/
#include <iostream>
using namespace std;

// 整体思路,先查找空格数量,然后从后向前依次复制字符

// 这种情况下,实现需要给定空间大小length,替换之后的字符串长度不能超过该length,否则会内存溢出


class Solution{
public:
void replaceSpace(char *str, int length){ // length 是字符数组总长度
/* 查找str中空格个数,构造新的字符串序列 */
int strLen = strlen(str);
cout << strLen << endl;
if (strLen == 0) return;
char *p = str;
int spaceNum = 0;
while(*p!='\0'){
if (*p == ' ') spaceNum ++;
p++;
}
cout << spaceNum << endl;
if (spaceNum == 0) return; // 无空格,返回
int newLen = strLen + 2*spaceNum;
if (newLen > length){ // 原数组长度不足
cout << "# Error: char array over flow!" << endl;
return;
}
str[newLen] = '\0'; // 注意最后一个字符应该是字符串终止字符,否则可能出错
for(int i = strLen -1, j = newLen-1; i>=0; i--){
if (spaceNum == 0) return;
// i for new, j for old, backword
if(str[i] == ' ') {
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
spaceNum --;
}else{
str[j--] = str[i];
}
}
}
};




int main(){
char char_array[30] =" hello world";
Solution sol;
sol.replaceSpace(char_array, 30);
cout << char_array<< endl;
system("pause");
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值