题目:请实现一个函数,把字符串中的每个空格替成“%20”。例如输入“we are happy.”,则输出“we%20are%20happy.”。
基本思路:先遍历一遍字符串统计字符串中空格的个数并计算出替换之后的字符串的总长度,每替换一个空格,长度增加2,因此替换后字符串的长度对于原来的长度加上空格个数的2倍。如果从头到尾扫描字符串,遇到空格就做替换,必须每次都把空格后面所有的字符都向后移动两个字节,这样处理的时间复杂度为O(n²),效率比较低。我们还有更好的方法, 从字符串的后面开始复制(没遇到空格)和替换(遇到空格),这样所有的字符都只复制(移动)一次,时间复杂度为O(n)。提高了效率
1.数组方法
#include <iostream>
using namespace std;
void ReplaceBlank(char str[], int length)
{
if (NULL == str && length <= 0)
return;
int oldLength = 0; //字符串实际长度
int num = 0; //空格个数
int i = 0;
while(str[i] != '\0')
{
oldLength++;
if (str[i] == ' ')
num++;
i++;
}
int newLength = oldLength + num * 2;
if (newLength > length)
return;
int tmp1 = oldLength;
int tmp2 = newLength;
while(tmp1 >= 0 && tmp2 > tmp1)
{
if (str[tmp1] == ' ')
{
str[tmp2--] = '0';
str[tmp2--] = '2';
str[tmp2--] = '%';
}
else
{
str[tmp2--] = str[tmp1];
}
tmp1--;
}
}
int main()
{
char str[100] = "We are happy";
int length = sizeof(str);
ReplaceBlank(str, length);
printf("%s\n", str);
return 0;
}
2.指针方法
#include <stdio.h>
#define MAX 100
void ReplaceBlank(char string[])
{
if(string==NULL)
return;
int count = 0;
int counts = 0;
char *p=string;
int i = 0;
while(*p !='\0')
{
if(*p == ' ')
{
counts++;
}
p++;
count++;
}
//判断是否越界
if((count + counts *2) >= MAX)
return;
//需要两个遍历指针
char *p1=p;
char *p2=p;
p2=p+2*counts;
*p2='\0';
for( i=0;i<count;i++)
{
if(*p1==' ')
{
*p2--='0';
*p2--='2';
*p2--='%';
}
else
*p2--=*p1;
p1--;
}
}
int main()
{
char str[MAX]="We are happy.";
ReplaceBlank(str);
printf("%s\n",str);
return 0;
}