題目:實現一個函數,把字符串中的每個空格替換成“%20”。例如輸入“We are happy.”,則輸出”We%20are%20happy.”
題目很簡單,直接上代碼
#include<iostream>
using namespace std;
void Replace(char string[],int length)
{
if(string==NULL || length<0)
{
return;
}
int originalLength=0;
int newLength =0;
int numberofBlank =0;
int i=0;
while(string[i]!='\0')
{
++originalLength;
if(string[i]==' ')
{
++numberofBlank;
}
++i;
}
newLength=originalLength+numberofBlank*2;
int indexofOriginal=originalLength;
int indexNew=newLength;
if(newLength>length)
{
return;
}
while(indexofOriginal>0 && indexofNew>indexofOriginal)
{
if(string[indexofOriginal]==' ')
{
string[indexofNew--]='0';
string[indexofNew--]='2';
string[indexofNew--]='%';
}
else{
string[indexofNew--]=string[indexofOriginal];
}
--indexofOriginal;
}
}
int main()
{
char string1[50]="Nothing is impossible!";
char string2[50]="My name is CSDN.";
char string3[50]="We are happy.";
Replace(string1,50);
Replace(string2,50);
Replace(string3,50);
cout<<string1<<endl;
cout<<string2<<endl;
cout<<string3<<endl;
system("pause");
return 0;
}