替换空格

'''
先遍历整个字符串,计算字符串中空格的总数,从而可以计算出替换后的字符串长度
(根据替换规则,每次替换空格时,都会使字符串的长度增加2)。然后,使用两个指针或索引,从后往前遍历,
即初始化指针或索引分别指向替换前和替换后字符串的末尾,循环递减,如遇到空格,则替换为 "%20",
从而减少字符串移动的次数,降低时间复杂度。
'''

def replace_blanks(string):
    if string == None : 
        return
    # Count the number of blanks
    blanks_count = string.count(' ')
    string_length = len(string)
    # Compute the replaced string length
    replaced_length = string_length + 2 * blanks_count
  
    # Extend the char list length 'string_length' with '' characters
    string += ["" for i in range(replaced_length - string_length)]
    print(string)
    # Replace each blank with "%20"
    original_index = string_length - 1
    new_index = replaced_length - 1
    while new_index != original_index:
        if string[original_index] == ' ':
            new_index -= 2
            string[new_index:new_index+3] = '%20'
        else:
            string[new_index] = string[original_index]
        # Update indexes
        new_index -= 1
        original_index -= 1


def unitest():
    test_string = "We are happy."
    string_lst = list(test_string)  # 易错点,不能用'str'对象替代,因为 'str' object does not support item assignment 。
    # print "Before replacing blanks, the string is %s" % ''.join(string_lst)
    print("Before the string is % s"% ''.join(string_lst))
    replace_blanks(string_lst, 100)
    # print "After replacing blanks, the string is %s" % ''.join(string_lst)
    print("After the string is % s"% ''.join(string_lst))


if __name__ == '__main__':
    unitest()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值