//进行空格的替换
#include<iostream>
using namespace std;
void ReplaceBlank(char str[],int length){
if(str==NULL||length<=0) return ;
int orignallength=0;//字符符串的实际长度
int blankNum=0;
int i=0;
for(i=0;str[i]!='\0';i++){
orignallength++;
if(str[i]==' ')
blankNum++;
}
int newlength=orignallength+blankNum*2;
if(newlength>length) return;
while(orignallength>=0&&newlength>orignallength){
//当字符串没有空格时,就会出现newlength=origallength的情况,从而减少复制操作
if(str[orignallength]==' '){
str[newlength--]='0';
str[newlength--]='2';
str[newlength--]='%';
}else{
str[newlength--]=str[orignallength];
}
orignallength--;
}
cout<<str<<endl;
}
void main(){
const int length=100;
char a[length]="hello world!";
ReplaceBlank(a,length);
char b[length]=" helloworld!";
ReplaceBlank(b,length);
char c[length]="helloworld! ";
ReplaceBlank(c,length);
char d[length]="hello world!";
ReplaceBlank(d,length);
ReplaceBlank(NULL,length);
char e[length]="";
ReplaceBlank(e,length);
char f[length]=" ";
ReplaceBlank(f,length);
char g[length]=" ";
ReplaceBlank(g,length);
char h[length]="helloworld!";
ReplaceBlank(h,length);
}
ReplaceBlank
最新推荐文章于 2021-03-02 07:37:11 发布