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 "\nelse"
    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 "\nelse"
    print "out of while"
simu_split(" ")
print "end of the file"

 

posted @ 2014-06-19 10:47  北冥飞鱼  阅读(2989)  评论(0编辑  收藏  举报