替换字符串中空格为%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
原创粉丝点击