剑指offer编程题——04 替换空格

//写函数,将字符串中的每个空格替换成20%
// 首先找出所有的空格数,然后整体后移,最后填充三个字符
/* 特殊字符可能会无法显示,需要ASCII码转换,%32空格*/
#include <iostream>
#include <cstring>
using namespace std;
char* replacestr(char str[]){
	//没必要定义新的数组,因为str足够大,直接后移元素即可
	
	if (str == NULL  || strlen(str) == 0)/*注意:先判断传入的参数是否空!*/
		return NULL;
	int len = strlen(str);
	int count = 0;
	int i = 0;
	while (count < len && i < len){
		if (str[i++] == ' ')
			++count;
	}
	int length = len + count * 2;
	i = len;
	while (i >= 0){
		if (str[i] == ' '){
			str[length--] = '0';
			str[length--] = '2';
			str[length--] = '%';
		}
		else
			str[length--] = str[i];
		--i;			
	}
	return str;	
}
// ====================== ERROR ================
char* replace_blank(char* str, int len){
	if (str == NULL || len <= 0)  
		return 0;
	int cnt = 0, length = strlen(str);
	while (*str != '\0'){
		if (*str++ == ' ')
			++cnt;
	}
	int total = length + cnt * 2;
	if (len < total)  
		return 0;
	
	int i = length;
	while (i >= 0){
		if (str[i] == ' '){
			str[total--] = '0';
			str[total--] = '2';
			str[total--] = '%';			
		}
		else
			str[total--] = str[i];
		
		--i;
	}
	return str;
}
void main04(){
	char str[20] = "I am happy";
	for (int i = 0; i < strlen(str); ++i){
		cout << str[i];
	}cout << endl;
	int len = sizeof(str)/sizeof(str[0]);
	char* s1 = replacestr(str);
	char str1[20] = "We are no";
	char* s2 = replace_blank(str1, len);
	for (int i = 0; i < strlen(str); ++i){
		cout << str[i];
	}
	cout << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值