#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
void ReplaceBlank(char str[], int length)
{
if(str == nullptr)
return;
int len = strlen(str);
int blankspacecnt=count_if(str, str+len,[](char c){return c==' ';}); //统计空格数目
int extra = 2*blankspacecnt;
if(len+extra > length) return; //字符数组长度不够,不能完全扩展
int i = len-1;
int j = len-1 + extra;
str[j+1] = '\0';
for(; blankspacecnt>0; )
{
if(str[i] != ' ')
{
str[j--] = str[i--]; //从后向前
}
else
{
str[j--] = '0'; //替换空格
str[j--] = '2';
str[j--] ='%';
i--;
blankspacecnt--;
}
}
}
int main()
{
char str[20];
strcpy(str, "we are happy.");
ReplaceBlank(str, 20);
cout<<str;
}
4.空格替换
最新推荐文章于 2024-02-12 18:10:33 发布