剑指offer上面的一道题。例如字符串是we are happy.
输出 we%20are%20happy.
如果按照基本的思路从前到后遍历字符串,每次识别到空格后面的字符就要往后移动两个位。因此用从后向前的方式
先计算出替换后的数组的长度。设置两个指针一个指向新数组的尾部,另一个指向原来数组的尾部。直到两个指针的数值相同时表示遍历完成。
代码如下。
#include<stdlib.h>
#include<iostream>
#include<stdio.h>
#include<vector>
#include<cmath>
#include<string.h>
using namespace std;
void replaceblank(char string[],int length)
{
int space=0;
int nospace=0;
int i=0;
int reallength=0;
if(string==null&&length<=0)
return;
while(string[i]!='\0')
{
reallength++;
if(string[i]==' ')
space++;
else
nospace++;
i++;
}
int newlength=reallength+space*2;
int a=reallength;
int b=newlength;
while(b>a)
{
if(string[a] == ' ')
{
string[b--]='0';
string[b--]='2';
string[b--]='%';
a--;
}
else
{
string[b--]=string[a--];
}
}
}
int main() {
char string[18]={"we are happy"};
replaceblank(string,18);
cout<<string<<endl;
}