码迷,mamicode.com
首页 > 其他好文 > 详细

替换空格

时间:2020-03-07 19:13:23      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:字符串   pac   public   ace   style   class   oid   lang   solution   

题目描述

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

C++11(clang++ 3.9)

class Solution {
public:
    void replaceSpace(char *str,int length) {
        // input check
        if(length <= 0)
        {
            return;
        }
        
        int space_count = 0;
        for(int i = 0; i < length; i++)
        {
            if(str[i] ==  )
            {
                space_count++;
            }
        }
        
        int new_index = length + space_count * 2 - 1;
        for(int i = length - 1; i >= 0; i--)
        {
            if(str[i] !=  )
            {
                str[new_index--] = str[i];
            }
            else
            {
                str[new_index--] = 0;
                str[new_index--] = 2;
                str[new_index--] = %;
            }
        }
    }
};

 

替换空格

标签:字符串   pac   public   ace   style   class   oid   lang   solution   

原文地址:https://www.cnblogs.com/hotwater99/p/12436110.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!