替换字符串中空格为%20
来源:互联网 发布:js获取浏览器高度 编辑:程序博客网 时间:2024/04/29 01:18
/*
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
*/
#include <iostream>
#include <cstring>#include <cstdlib>
#include <cstdio>
using namespace std;
/*
方法一:
创建足够长的新存储空间
*/
void replaceSpace_1(char* str)
{
char* str1 = (char*)malloc(100);
char *s = str1;
//注意不要直接移动原来的指针,如果直接移动原来的指针,那么最后这个指针就不指向原来创建的地址头,导致输出失败 ;
if(s == NULL ||str == NULL)
return;
while(*str != '\0')
{
//if(*str++ == ' ') 这个是错的 如果判断不是空 这个时候也会使指针移动 导致遗漏 因为这句执行完之后,str就指向下一位了
if(*str == ' ')
{
*s++ = '%';
*s++ = '2';
*s++ = '0';
}
else
{
*s++ = *str;
}
str++;
}
*s = '\0';
puts(str1);
free(str1);
}
/*
方法二:
假设原来输入的字符串长度很长,在原输入的基础上直接操作 注意要从后往前插入,可以减少移位的次数
*/
void replaceSpace_2(char* str,int length){
if(str == NULL || length <= 0)
return;
char *s = str;
int lenofstr = 1;
int numofblank = 0;
while(*s != '\0'){
lenofstr++;
if(*s == ' ')
numofblank++;
s++;
}
int newlength = lenofstr + 2*numofblank;
if(newlength > length)
return;
int index1 = lenofstr - 1;
int index2 = newlength - 1;
while(index1 >= 0 && index2 > index1){
if(str[index1] == ' ')
{
str[index2--] = '0';
str[index2--] = '2';
str[index2--] = '%';
}
else
{
str[index2--] = str[index1];
}
index1--;
}
cout << str << endl;
}
int main()
{
char s[100] = "we are happy new year.";
//replaceSpace_1(s);
replaceSpace_2(s,100);
return 0;
}
0 0
- 把字符串中空格替换为"%20"
- 替换字符串中空格为%20
- 字符串中空格替换为%20(算法)
- 剑指offer - 将字符串中空格替换为20%
- 替换空格(将字符串中的空格替换为20%)
- 1.5-替换字符串中的空格为%20
- 将字符串中的空格替换为“20%”
- 替换字符串中的空格为%20--20150925
- 替换字符串中的空格为%20
- 把字符串中的空格替换为"%20"
- 将字符串中的空格替换为%20
- 将字符串中的空格替换为“%20”
- 将字符串中的空格替换为%20
- 替换字符串中空格
- 替换字符串中空格
- 字符串中替换空格
- 字符串中替换空格
- 程序员面试金典: 9.1数组与字符串 4字符串中空格全部替换为"%20"
- linux环境下找出今天被修改的文件
- Hadoop Yarn 框架原理及运作机制
- CentOS6.5_64位系统下安装配置postfix邮件系统 启用并配置SMTP在第三方上边使用发送邮件
- 3.9触摸事件分发的例子-选择英雄图标,切换对应英雄,控制其移动。
- PAT BASIC LEVEL 1005. 继续(3n+1)猜想 (25)
- 替换字符串中空格为%20
- http学习笔记(模拟http请求和响应过程)
- HTML学习笔记(1)
- Markdown使用
- c语言----函数的递归
- 关键字const
- 也谈10000小时
- HTTPS和HTTP的区别
- C++实现谢尔排序(希尔排序)(shell sort)