String length without len function

前端 未结 17 1172
逝去的感伤
逝去的感伤 2020-12-10 21:29

Can anyone tell me how can I get the length of a string without using the len() function or any string methods. Please anyone tell me as I\'m tapping my head ma

相关标签:
17条回答
  • 2020-12-10 21:47
    >>> import re
    >>> s
    'mylongstring'
    >>> re.subn(".","1",s)[-1]
    12
    >>>
    

    If string contains new lines

    >>> s="mys\ntring\n"
    >>> re.compile(".",re.DOTALL).subn("",s)[-1]
    10
    
    0 讨论(0)
  • 2020-12-10 21:48

    Here's an O(1) method:

    def strlen(s):
        if s == "": return 0
        return s.rindex(s[-1]) + 1
    

    In other words, it doesn't work by counting the characters, so should be just as fast for a 1GB string as it is for a 1 byte string.

    It works by looking at the last character and searching from the very end to find that character. Since it's the last character it will always find it at the first place it looks, essentially always returning the index of the last character. The length is just one more than the index of the last character.

    0 讨论(0)
  • 2020-12-10 21:48

    Here's a way to do it by counting the number of occurences of the empty string within the string:

    def strlen(s):
        return s.count('') - 1
    

    Since "".count("") returns 1, you have to subtract 1 to get the string's length.

    0 讨论(0)
  • 2020-12-10 21:51
    a = 'malayalam'
    length = 0
    for i in a:
        if i == "":
            break
        else:
            length+=1
    
    print length
    

    This code verifies the length of a string by counting until ""(end of the string ).If the string reaches an end, the loop breaks and will return the final length of the string.

    0 讨论(0)
  • 2020-12-10 21:55

    Make a file-like object from the string, read the entire object, then tell your offset:

    >>> import StringIO
    >>> ss = StringIO.StringIO("ABCDEFGHIJ")
    >>> ss.read()
    'ABCDEFGHIJ'
    >>> ss.tell()
    10
    
    0 讨论(0)
  • 2020-12-10 21:56

    Using while loop

    a = 'string'
    count = 0
    
    while True:
        try:
            if a[count]:
                count += 1
        except IndexError as e:
            break
    
    print(count)
    
    0 讨论(0)
提交回复
热议问题