【附加题】--替换字符串中的空格为$$$。要求时间复杂度为O(N)
例如:将"talk is cheap show me the code"替换。为"talk$$$is$$$cheap$$$show$$$me$$$the$$$code"。
解题思路:
1.先求出原字符串中空格的个数NumBerOfBlank;
2.求出源字符串的的字符个数(不含‘\0’)OldLength;
3.求出加上替换符以后的新字符串的长度NewLength;
4.要判断新字符串字符个数和字符数组总大小的关系;避免访问越界,造成系统崩溃;
5.分别从原字符串的末尾和新字符串的末尾从后向前将原字符串的字符拷贝到新字符串对应的位置;期间原字符指针遇见了空格,那么原字符指针向后走一步,新字符指针向前走三步,每一步将要替换的字符填入指针所对应的位置;
6.直到源字符串访问完毕,或者新旧字符指针相遇,说明此时空格替换完毕;
#include<iostream>
#include<cassert>
using namespace std;
//空格替换函数
void ReplaceBlank(char* str,int len)
{
//1.排除异常情况
if (str==NULL||len<0)
{
return ;
}
//2.求加上$替换符以后的长度
int OldLength=0;//源字符串长度
int NumBerOfBlank=0;//统计空格的个数
int NewLength=0;//加上$替换符以后的字符串总长度
char* cur=str;
while (*cur!='\0')
{
if (*cur==' ')
{
NumBerOfBlank++;//统计空格
}
cur++;
OldLength++;
}
NewLength=NumBerOfBlank*2+OldLength;//把$加上以后的长度
if (NewLength+1>len)
{
return ;
}
cur=str;
//3.开始替换空格
while (OldLength>=0&&OldLength<NewLength)
{
if (str[OldLength]==' ')
{
OldLength--;
str[NewLength--]='$';
str[NewLength--]='$';
str[NewLength--]='$';
}
else
{
cur[NewLength--]=cur[OldLength--];
}
}
}
//1.空格在中间
void test1()
{
char str[50]="talk is cheap show me code";
printf("%s\n",str);
ReplaceBlank(str,50);
printf("%s\n",str);
};
//2.两端也有空格
void test2()
{
char str[50]=" talk is cheap show me code ";
printf("%s\n",str);
ReplaceBlank(str,50);
printf("%s\n",str);
};
//3.没有主体,只有空格的字符串
void test3()
{
char str[50]=" ";
printf("%s\n",str);
ReplaceBlank(str,50);
printf("%s\n",str);
};
//空字符串
void test4()
{
char str[50]="";
printf("%s\n",str);
ReplaceBlank(str,50);
printf("%s\n",str);
};
int main()
{
/*test1();*/
/*test2();*/
/*test3();*/
test4();
return 0;
}