【剑指**】5.替换空格
来源:互联网 发布:python 函数传递对象 编辑:程序博客网 时间:2024/06/07 05:11
5. 替换空格
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路
思路就是书上的思路。两个指针操作。
传入的指针实际上上是数组头;
注意参数 length 不是字符的长度,而是数据空间的长度;
所以,字符的长度,要根据 ‘\0’ 的条件,自己去计算一遍;
好久没写指针,都忘了 怎么遍历值了。。。。
代码
class Solution {public: void replaceSpace(char *str,int length) { if (str == NULL || length <= 0) return; int n_blank = 0; int actual_length = 0; int i = 0; while (*(str + i) != '\0') { actual_length++; if ( *(str + i) == ' ' ) n_blank++; i++; } int new_len = actual_length + 2*n_blank; if (new_len > length) return; int idx_1 = actual_length; int idx_2 = new_len; while (idx_1 >= 0 && idx_1 < idx_2) { if (*(str+idx_1) != ' ') { *(str + idx_2) = *(str+idx_1); idx_2--; } else { *(str + idx_2) = '0'; idx_2--; *(str + idx_2) = '2'; idx_2--; *(str + idx_2) = '%'; idx_2--; } idx_1--; } }};
阅读全文
0 0
- 【剑指**】5.替换空格
- [剑指offer]替换空格
- [剑指offer]替换空格
- 剑指offer:替换空格
- 替换空格--《剑指offer》
- 剑指Offer:替换空格
- 【剑指offer】替换空格
- 剑指Offer4 替换空格
- 《剑指Offer》--替换空格
- 剑指offer--替换空格
- 【剑指offer】替换空格
- 【剑指offer】空格替换
- 剑指offer-替换空格
- 剑指offer:替换空格
- [剑指offer]替换空格
- 《剑指offer》替换空格
- 剑指offer:替换空格
- 【剑指Offer】替换空格
- 移动磁盘磁盘结构损坏且无法读取要如何办啊
- Angular2-使用Angular CLI快速搭建工程
- OpenGL入门学习
- orcl索引失效,重建所有索引,或者根据命名空间重建所有索引
- 技术专题讨论:JPA vs MyBatis ?您如何选择?(有奖活动)
- 【剑指**】5.替换空格
- GYM 101522B. Bacteria Experiment
- Tablayout+Frament+ViewPager
- C++学习之入门求平均数
- Maven导入建立父子项目时的问题
- Android SDK | API level 24 | GestureDetector
- WebView简单使用
- localhost:8080/项目名称
- node使用