zoukankan      html  css  js  c++  java
  • 《剑指offer

    题目描述

    请实现一个函数,将一个字符串中的每个空格替换成“%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-- = '';
            while (strLength >= 0) {
                if(*tail == ' '){
                    *newTail-- = '0';
                    *newTail-- = '2';
                    *newTail-- = '%';
                }
                else{
                    *newTail-- = *tail;
                }
                tail--;
                strLength--;
            }
        }
    };
    

      

  • 相关阅读:
    1.8 Hello World添加menu
    1.7 HelloWorld 添加视图
    1.6 Hello World
    1.5 组件开发基础
    awk
    sed
    grep / egrep
    Shell基础知识
    和管道符有关的命令
    Shell变量
  • 原文地址:https://www.cnblogs.com/doudouyoutang/p/9897949.html
Copyright © 2011-2022 走看看