替換空格[by Python]
阿新 • • 發佈:2018-11-05
題目:
請實現一個函式,將一個字串中的空格替換成“%20”。例如,當字串為We Are Happy.則經過替換之後的字串為We%20Are%20Happy。
1.使用python自帶的replace方法:
# -*- coding:utf-8 -*- # -*- python3.6.6 -*- # -*- JluTiger -*- # -*- 替換空格 -*- class Solution: # s 源字串 def replaceSpace(self, s): # write code here return s.replace("","%20") if __name__=="__main__": s="we are famliy" answer = Solution().replaceSpace(s) print(answer)
2.對空格使用split,再使用“%20”連線:
class Solution: # s 源字串 def replaceSpace(self, s): # write code here return '%20'.join(s.split(' ')) if __name__=="__main__": s="we are famliy" answer = Solution().replaceSpace(s) print(answer)
3.由於替換空格後,字串長度需要增大。先掃描空格個數,計算字串應有的長度,從後向前一個個字元複製(需要兩個指標)。這樣避免了替換空格後,需要移動的操作:
class Solution: # s 源字串 def replaceSpace(self, s): # write code here #計算有多少個空格 num_space = 0 for i in s:if i == ' ': num_space += 1 #新的字串的長度 new_length = len(s) + 2 * num_space index_origin = len(s) - 1 index_new = new_length - 1 #新的字串 new_string = [None for i in range(new_length)] #按照從後往前的順序將%20填入 while index_origin >= 0 & (index_new > index_origin): if s[index_origin] == ' ': new_string[index_new] = '0' index_new -= 1 new_string[index_new] = '2' index_new -= 1 new_string[index_new] = '%' index_new -= 1 else: new_string[index_new] = s[index_origin] index_new -= 1 index_origin -= 1 return ''.join(new_string) if __name__=="__main__": s="we are famliy" answer = Solution().replaceSpace(s) print(answer)