zoukankan      html  css  js  c++  java
  • 替换空格

    题目描述

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

    思路

    第一步先遍历整个字符串,确定其中有多少个空格。

    将字符串的长度增长,增长空格数乘以2。

    第三个,重新遍历字符串,遍历的顺序为倒序,从字符串的最后一个字符往前遍历,如果不是空格,增加字符串添加到增长后的字符串的末尾,这里的添加类似于入栈操作,如果是空格,增将空格替换为“%20”。

    class Solution {
    public:
        void replaceSpace(char *str,int length) {
            if(str == NULL || length <= 0) return;
            int count_space = 0;
            int curr_count_space = 0;
            for(int i = 0; i < length; i++)
                if(str[i]==' ') count_space++;
            str[length + count_space*2] = '';
            for(int i = 0; i < length + count_space*2; i++){
                if(str[length - 1 - i] == ' '){
                    str[length + count_space*2- 1 - i - curr_count_space*2] = '0';
                    str[length + count_space*2- 2 - i - curr_count_space*2] = '2';
                    str[length + count_space*2- 3 - i - curr_count_space*2] = '%';
                    curr_count_space++;
                }
                else str[length + count_space*2- 1 - i - curr_count_space*2] = str[length - i - 1];
            }
        }
    };
  • 相关阅读:
    用户模板和用户场景
    移动端疫情展示
    数据爬取
    全国疫情统计可视化地图-第二、三阶段
    学习进度条-第三周
    学习进度条-第二周
    软件工程第二周开课博客
    返回一个整数数组中最大子数组的和
    JavaWeb选课系统(2)
    JavaWeb选课系统
  • 原文地址:https://www.cnblogs.com/zhousong918/p/10266722.html
Copyright © 2011-2022 走看看