面试题5:空格的替换

/*!
 * @file     题目五、替换空格.cpp
 * @Date:    2018/01/27 10:32
 * @author:  sicaolong
 * @Contact: sicaolong@163.com
 * @brief:   
 * @TODO: 
*/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================

// 面试题5:替换空格
// 题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入“We are happy.”,
// 则输出“We%20are%20happy.”。
#include<iostream>
#include <string>
using namespace std;
void replace_space(char *str, char*);
int count_number(char *);
int main()
{
	char s[] = "I love you.";
	char *str1= s;//声明一个指针str1指向这个数组
	cout << "空格替换之前的字符串为str1:" << str1 << endl;
	int len1 = sizeof(s) / sizeof(char);//根据原来的数组求出数组的长度
	cout << "str1的长度为:" << len1 << endl;

	int number_space = count_number(str1);//计算空格的个数;并输出
	cout << "number_space=" << number_space << endl;

	char *str2 = new char[len1 + number_space * 2];//为str2 分配内存空间
	replace_space(str1, str2);//执行替换空格操作;
	cout <<"空格替换后的字符串为:"<< str2 << endl;
	
}
void replace_space(char *str1, char*str2)
{
	while (*str1)//当str1存在的时候执行操作
	{
		if (*str1 != ' ')//当str1[i]不为空格赋值给str2;
		{
			*str2 = *str1;
			str2++;
		}
		else//当str1[i]为空格的时候,把"***"拷贝到str2中;并且指针往后移3位;
		{
			strcpy(str2, "***");
			str2 += 3;
		}
		str1++;
	}
	*str2 = '\0';
}
int count_number(char * str)//计算字符串中的空格数
{
	int i = 0;
	
	int number_space = 0;
	while (str[i]!='\0')
	{
		if (str[i] == ' ')
			number_space++;
		++i;
	}
	return number_space;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值