替换空格

仅作为个人笔记

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


C++

class Solution {
public:
    void replaceSpace(char *str,int length) {
        if(str == NULL && length <= 0)
            return;

        int originalLength = 0;
        int numberOfBlank = 0;
        int i = 0;
        while(str[i] != '\0')
        {
            ++originalLength;

            if(str[i] == ' ')
                ++numberOfBlank;

            ++i;
        }

        int newLength = originalLength + numberOfBlank * 2;
        if(newLength > length)
            return;

        int indexOfOriginal = originalLength;
        int indexOfNew = newLength;
        while(indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
        {
            if(str[indexOfOriginal] == ' ')
            {
                str[indexOfNew--] = '0';
                str[indexOfNew--] = '2';
                str[indexOfNew--] = '%';
            }
            else
            {
                str[indexOfNew--] = str[indexOfOriginal];
            }
            --indexOfOriginal;
        }

    }
};

Java

public class Solution {
    public String replaceSpace(StringBuffer str) {
        if(str == null)
            return null;

        StringBuffer newStr = new StringBuffer();
        for(int i = 0; i < str.length(); i++)
        {
            if(str.charAt(i) == ' ')
            {
                newStr.append('%');
                newStr.append('2');
                newStr.append('0');
            }
            else
            {
                newStr.append(str.charAt(i));
            }
        }
        return newStr.toString();
    }
}

public class Solution {
    public String replaceSpace(StringBuffer str) {
        return str.toString().replaceAll("\\s", "%20");
    }
}

Python

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        return s.replace(' ', '%20')
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        index = range(len(s)-1,-1,-1)
        for i in index:
            if s[i].isspace():
                s = s[:i] + "%20" + s[i+1:]
        return s
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Shingle_/article/details/52347778
个人分类: nowcoder
上一篇二维数组中的查找(行递增矩阵的查找)
下一篇从尾到头打印链表
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭