面试题4:替换空格

来源:互联网 发布:淘宝考试题目答案 编辑:程序博客网 时间:2024/06/06 04:27

面试题4:替换空格


提交网址: http://www.nowcoder.com/practice/4060ac7e3e404ad1a894ef3e17650423?tpId=13&tqId=11155


参与人数:10327 时间限制:1秒 空间限制:32768K
本题知识点:字符串

题目描述


请实现一个函数void replaceSpace(char *str,int length),将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。


分析:


AC代码

文件名: AimedAtOffer-replaceSpace.cpp

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include<iostream>  
  2. #include<string>  
  3. #include<cstdio>  
  4. using namespace std;  
  5.   
  6. class Solution{  
  7. public:  
  8. void replaceSpace(char *str, int length)  
  9. {  
  10.     if(str==NULL || length<=0) return;  
  11.       
  12.     int newlen=0;  
  13.     int spaceCount = 0;  
  14.     int idx;  
  15.     for(idx = 0; str[idx] != '\0'; idx++)  
  16.     {  
  17.         if (str[idx] == ' ')  
  18.         {  
  19.             spaceCount++;  
  20.         }  
  21.     }  
  22.     newlen = idx + 2*spaceCount;  
  23.     if(newlen > length) return;  
  24.     str[newlen]='\0';  //此行很关键   
  25.     int frontCur = idx - 1, backCur = newlen-1;  
  26.     for(; frontCur >= 0 && backCur > frontCur; frontCur--)  
  27.     {  
  28.         if (str[frontCur] == ' ')  
  29.             {  
  30.             str[backCur--] = '0';  
  31.             str[backCur--] = '2';  
  32.             str[backCur--] = '%';  
  33.             }  
  34.         else str[backCur--] = str[frontCur];  
  35.     }  
  36. }  
  37. };  
  38.   
  39. // 以下为测试部分  
  40. /* 
  41. int main() 
  42. { 
  43.     Solution sol; 
  44.     char str[]="Hello World, haha"; 
  45.     sol.replaceSpace(str, 20); 
  46.     // printf("%s\n",str); 
  47.     cout<<str<<endl;     
  48.     return 0; 
  49. } 
  50. */  
0 0
原创粉丝点击