def replaceSpace(str):
""""
实现一个函数,字符串中每个空格替换成"%20"
"""
count =0
for i in str:
if i == " ":
count += 1
lenghth2 = len(str)+count*2
str2 = [0]*lenghth2
i = len(str)-1
j = len(str2)-1
while(i>=0):
if(str[i]!=" "):
str2[j] = str[i]
j -= 1
i -= 1
if(str[i] ==" "):
str2[j-2]="%"
str2[j-1]="2"
str2[j]="0"
i -= 1
j -= 3
return str2
if __name__ == '__main__':
str = "we are happy"
result = replaceSpace(str)
print(str)
print(result)
剑指offer4(python)
最新推荐文章于 2024-05-13 08:40:16 发布
本文介绍了一种将字符串中的空格替换为%20的算法实现,通过遍历字符串并计算空格数量,调整目标字符串长度,再从后向前逐字符复制,遇到空格则替换成%20,最终返回处理后的字符串。
9988

被折叠的 条评论
为什么被折叠?



