URL化
文字列内のすべてのスペースを%20に置き換えるメソッドを記述します。文字列の最後には新しい文字を格納するのに十分なスペースがあり、文字列の「実際の」長さがわかっていると想定されます。
例1:
- 入力:「ジョン・スミス氏」、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)