URL化 替换空格
发布日期:2021-05-07 08:24:11 浏览次数:24 分类:精选文章

本文共 1044 字,大约阅读时间需要 3 分钟。

URL化 替换空格

编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。

示例 1:

  • 输入:"Mr John Smith    ", 13
  • 输出:"Mr%20John%20Smith"

示例 2:

  • 输入:"               ", 5
  • 输出:"%20%20%20%20%20"

示例代码1:

#  方法一:调用库函数class Solution(object):    def replaceSpaces(self, S, length):        """        :type S: str        :type length: int        :rtype: str        """        return S[:length].replace(' ', '%20')a = Solution()# b = a.replaceSpaces("Mr John Smith    ", 13)# b = a.replaceSpaces("Mr John Smith    ", 14)b = a.replaceSpaces("               ", 5)print(b)

示例代码2:

#  方法二:单纯耿直的循环替换class Solution(object):    def replaceSpaces(self, S, length):        """        :type S: str        :type length: int        :rtype: str        """        URL = []        for char in S[:length]:            if char == ' ':                URL.append('%20')            else:                URL.append(char)        return ''.join(URL)a = Solution()# b = a.replaceSpaces("Mr John Smith    ", 13)# b = a.replaceSpaces("Mr John Smith    ", 14)b = a.replaceSpaces("               ", 5)print(b)

运行效果:

上一篇:回文排列
下一篇:判定是否互为字符重排

发表评论

最新留言

不错!
[***.144.177.141]2025年04月04日 22时42分48秒