/*!
* @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;
}
面试题5:空格的替换
最新推荐文章于 2020-04-03 22:23:42 发布