/**********************************************************
题目:请实现一个函数,把字符串中的每个空格替换成"%20"。
输入"We are happy.",则输出"We%20are%20happy."。
**********************************************************/
#include <stdio.h>
#include <string.h>
void replaceBlank(char* str, int length)
{
if(str == NULL || length <= 0) //注意判断传递的参数是否有效
return;
int strLength = strlen(str); //字符串长度
int blankCount = 0; //空格符出现次数
for(int i=0; i<strLength;i++)
{
if(str[i] == ' ')
++blankCount;
}
int newstrLength = strLength + 2 * blankCount; //改变后的字符串长度
char* p1 = str + strLength + 1; //辅助指针,指向原来字符串结束符,并向前移动
char* p2 = str + newstrLength + 1; //辅助指针,指向改变后字符串结束符,并向前移动
while(p1 != p2 && p1 >= str) //转换空格为%20
{
if(*p1 != ' ')
*p2 = *p1;
else
{
*p2 = '0';
*(--p2) = '2';
*(--p2) = '%';
}
--p1;
--p2;
}
return;
}
//单元测试
void test(char* str, int length)
{
printf("%s\n",str);
replaceBlank(str,length);
printf("%s\n",str);
}
//空格在中间
void test1()
{
const int length =100;
char string[length]= "We are happy.";
test(string,length);
}
//空格在开头
void test2()
{
const int length =100;
char string[length]= " We are happy.";
test(string,length);
}
//空格在结尾
void test3()
{
const int length =100;
char string[length]= "We are happy. ";
test(string,length);
}
//连续两个空格
void test4()
{
const int length =100;
char string[length]= "We are happy.";
test(string,length);
}
//都为空格
void test5()
{
const int length =100;
char string[length]= " ";
test(string,length);
}
//没有字符
void test6()
{
const int length =100;
char string[length]= "";
test(string,length);
}
//空指针
void test7()
{
const int length =100;
test(NULL,length);
}
int main()
{
test1();
test2();
test3();
test4();
test5();
test6();
test7();
return 0;
}
/*
这种方法的时间复杂度为O(n)
首先遍历一次字符串,这样就能统计出字符串中空格的总数,并可以由此计算出替换之后字符串的长度。每替换一个空格,长度增加2。然后设置两个指针,一个指针P1指向原来字符串
的的末尾,另一个指针P2指向替换后字符串的末尾。依次向前移动指针,并复制字符串的内容到
替换后的字符串中。每当P1碰到空格,则把空格换成‘%20’,P1向前移动一格,P2移动两格。
*/
==参考剑指offer面试题4