zoukankan      html  css  js  c++  java
  • 20190118-自定义实现replace方法

    1.自定义实现replace方法

    Python replace() 方法把字符串中的 old(旧字符串) 替换成 neange(新字符串),如果指定第三个参数max,则替换不超过 max 次。
    考虑old与nein的长度不一样的情况,如old = 'is';new = 'was'

    思路:

    1.先找出字符串中old字符的index,考虑可能出现多次的情况使用一个列表replace_str_index_in_s存储old_str的index

    2.使用result列表存储替换后的新的字符串,考虑result的生成方式为:

      2.1 从原有字符串的第0位开始,如果index不在replace_str_index_in_s中,则result+=s[i],然后查看i+1,i+2...

      2.2 如果index在replace_str_index_in_s中,则result+=new_str,此时需要注意的一点是新的i的位置位i+len(old_str)而非i+1

      2.3 考虑不知下一个i的值为i+1还是i+len(old_str),因此用while语句来实现

    3. 考虑给定max的情况使用count来计数,当count<max的时候替换,当count>max的时候不替换

    def customize_replace(s,old_str,new_str,max=None):
        result =''
        #存储新的字符串
        replace_str_index_in_s =[]
        #存储old_str的index
        for i in range(len(s)):
            if s[i:i+len(old_str)]==old_str:
                replace_str_index_in_s.append(i)
        j=0
        if max==None:
            while j <len(s):
                #遍历s[j],j的值不是按序+1,因此用while循环
                if j in replace_str_index_in_s:
                    result+=new_str
                    j+=len(old_str)
                else:
                    result+=s[j]
                    j+=1
        else:
            count =0
            #统计替换次数
            while j <len(s):
                if count <max and j in replace_str_index_in_s:
                    print('if执行',j,result)
                    result+=new_str
                    j+=len(old_str)
                    count+=1
                else:
                    print('else执行',j,result)
                    result+=s[j]
                    j+=1
        return result

    Tips:有一种特殊情况如s2='addbbdddbbbddbb##bb#'有3个b的情况下替换的old_str为bb的时候,因此replace_str_index_in_s里面的index可能结果为[3,8,9,13,17],但是明显第9位不会进行替换,因为此处需要用count来计数而不能写做replace_str_index_in_s[:max],这种写法的情况下会有替换次数不足max的情况,错误情况如max =3,那么replace_str_index_in_s[:3] = [3,8,9],但是第9位不会替换,因此实际替换次数为2,因此不能用这种写法

  • 相关阅读:
    第八讲、原型模式
    第七讲、建造者模式
    第六讲、抽象工厂模式
    第五讲、工厂方法模式
    第四讲、简单工厂模式
    第三讲、策略模式
    第二讲、备忘录模式
    第一讲、单例模式
    二、中国黑客
    java 17
  • 原文地址:https://www.cnblogs.com/hyj691001/p/10289520.html
Copyright © 2011-2022 走看看