/********************************************************** 题目:请实现一个函数,把字符串中的每个空格替换成"%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)
首先遍历一次字符串,这样就能统计出字符串中空格的总数,并可以由此计算出替换之后*/
==参考剑指offer面试题4
原文:http://blog.csdn.net/walkerkalr/article/details/20212511