题目描写叙述
请实现一个函数,将一个字符串中的空格替换成“%20”。
请实现一个函数,将一个字符串中的空格替换成“%20”。
比如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解题思路
这样的题目从前往后扫描的话。须要移动多次。
这样的情况下从后往前扫描。
首先扫描一遍。找到空格的个数,算出须要加入多少个20%,即替换后的字符串的长度 = 原字符串长度 + 空格数*2
准备两个指针一个指针p1指向当前字符串的最后位置,还有一个指针p2指向新字符串的最后位置。
然后依次向前扫描。当遇到空格的时候。p1向前移动一个位置,p2向前移动三个位置,而且依次用20%替换。
代码实现
class Solution { public://注意:length是整个字符串的总容量 包含未占用的空间 void replaceSpace(char *str, int length) { //首先推断边界条件,如空啥的 if (str == nullptr || length <= 0) return; int originLen = 0; int numOfblank = 0; int i = 0; while (str[i] != '