《剑指offer - 题目2》

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
 
注意方法参数中没有返回值,直接在原来的缓冲区中修改就可以了
 
#include <stdio.h>
#include <stdlib.h>
#include <string>

/*
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
*/

//从后面往前面开始复制

using namespace std;

class Solution {
public:
    void replaceSpace(char *str,int length) {
        char *head = str;
        int chrLength = 0;
        int spaceLength = 0;
        
        while (*head) {
            if(*head == ' '){
                spaceLength++;
            }
            else{
                chrLength++;
            }
            ++head;
            
        }
        if(spaceLength*2 + chrLength + 1 > length)
            return;
        int strLength = chrLength + spaceLength;
        char *tail = str + chrLength + spaceLength - 1;
        char *newTail = str + spaceLength*3 + chrLength;
        *newTail-- = '\0';
        while (strLength >= 0) {
            if(*tail == ' '){
                *newTail-- = '0';
                *newTail-- = '2';
                *newTail-- = '%';
            }
            else{
                *newTail-- = *tail;
            }
            tail--;
            strLength--;
        }
    }
};

  

posted @ 2018-11-02 19:06  兜兜有糖的博客  阅读(195)  评论(0编辑  收藏  举报