String splitting question

Rick Ratzel rlratzel at siliconmetrics.com
Wed Apr 9 03:19:55 EDT 2003


Jim Shady wrote:

> I have a string:
> 
> abcd/df/a/iiwk/abcdefghijkl/b/c
> 
> I need to get the longest string between the /s of the string. For
> example, longest_str() for the above line should return
> 'abcdefghijkl'. How do I go about doing this?

    I'm sure i'll be one of many to help, but FWIW:

#
# returns the longest substring in inString, as delimited by "/"
#
def longest_str( inString ) :

     currentLen = 0
     maxLen = 0
     biggestString = ""

     #
     # check each substring, save the biggest one
     #
     for subString in inString.split( "/" ) :

         currentLen = len( subString )

         if( currentLen > maxLen ) :
             biggestString = subString
             maxLen = currentLen

     return biggestString


#
# test
#
for ts in ["abcd/df/a/iiwk/abcdefghijkl/b/c",
             "",
             "//",
             "abcd/df4444444444444444//////iiwk/abcdefghijkl/b/c"] :

     print "BIGGEST SUBSTRING IN: %s IS: %s" % (ts, longest_str( ts ))





More information about the Python-list mailing list