空格替換
設(shè)計一種方法摸航,將一個字符串中的所有空格替換成 %20 。你可以假設(shè)該字符串有足夠的空間來加入新的字符舅桩,且你得到的是“真實的”字符長度酱虎。
你的程序還需要返回被替換后的字符串的長度。
空格替換
def replaceBlank(self, string, length):
# write your code here
if length == 0:
return 0
count = 0
for char in string:
if char == ' ':
count += 1
if count == 0:
return length
length_new = length + count * 2
str_new = [0] * length_new
i = length - 1
j = length_new - 1
while i != -1:
if string[i] == ' ':
string[j] = '0'
string[j - 1] = '2'
string[j - 2] = '%'
j -= 3
else:
string[j] = string[i]
j -= 1
i -= 1
return length_new