• split函数的实现


    split函数的功能是按照,一个指定的分隔符seperator,对字符串进行分割,形成很多子串。这是一个很常用的函数,每种语言的字符串相关的库函数中都有这个函数的实现。下面是我自己通过对split函数的理解,总结出的该函数的实现步骤:
    s="   ...faffaffj  wejl;ajf;l end jfjj  "
    1、利用find函数,找到第一个分隔符所在的位置,如果find返回-1,打印整个字符串s
    2、否则,寻找第一分隔符以后第一个不为分隔符的字符的位置p,打印从字符串的开始到p之间的子串
    3 从p开始寻找下一个分隔符q,p q之间就是一个分割
    4、重复上面的动作3
    下面是用python写的代码:
    def simu_split(sep):
        s1="www  neu   edu    cn"
        #s1=s1.strip()
        length=len(s1)
        print length
        a=s1.find(sep)
        n=len(sep)
        if a==-1:
            print s1
        elif:
            print s1[:a],
        while a<length and a!=-1:
            
            while a<length and s1[a:a+n]==sep ://这一步跟标准库的处理不同,标准库是遇到一个
                                                                //sep就打印
                a+=n
            b=a
            a=s1.find(sep,b)
            if a==-1:
                print s1[b:length],
            else:
                print s1[b:a],
        else:
            print "
    else"
        print "out of while"
    simu_split(" ")
    print "end of the file"
    上面是我自己的实现,下面的是标准库的实现。我自己实现的版本与标准库的实现版本的区别是:两个seperator相连时,标准库的是把两个seperator之间当作存在空格,输出;我的版本是跳过不进行输出。下面的是标准库的实现的python代码:
    def simu_split(sep):
        s1="www  neu   edu    cn"
        #s1=s1.strip()
        length=len(s1)
        print length
        a=s1.find(sep)
        n=len(sep)
        if a==-1:
            print s1
        elif:
            print s1[:a],
        while a<length and a!=-1:
            
            #while a<length and s1[a:a+n]==sep :
               # a+=n
            b=a
            a=s1.find(sep,b)
            if a==-1:
                print s1[b:length],
             elif (b-a)==n:
                   print "   "
            else:
                print s1[b:a],
        else:
            print "
    else"
        print "out of while"
    simu_split(" ")
    print "end of the file"
  • 相关阅读:
    九宫格拼图 支持44 55等
    js 怎样获取div 图片等的宽度,只要值,不要px
    spring boot单元测试之RestTemplate(一)
    java设计模式-原型(prototype)
    Hibernate注解(二):关联关系映射注解
    spring之@value详解二(转载)
    spring之@Value详解(转载)
    Spring之基于注解的注入
    Spring之bean生命始末
    Spring之bean后处理器
  • 原文地址:https://www.cnblogs.com/wangyichao/p/3796014.html
Copyright © 2020-2023  润新知