String length without len function

2019-01-26 02:25发布

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 madly for the answer.
Thank you.

15条回答
祖国的老花朵
2楼-- · 2019-01-26 02:37

Here's a method which isn't using neither len nor iteration:

>>> a = 'a' * 200000
>>> a.rindex(a[-1]) + 1
200000

To make it work for lists, which don't have rindex, use:

>>> a = list(range(200000))
>>> a.index(a[-1], -1) + 1
200000
查看更多
爷、活的狠高调
3楼-- · 2019-01-26 02:40

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.

查看更多
太酷不给撩
4楼-- · 2019-01-26 02:40
def length(object):#Define the length calculation function

    count = 0  #initializing the length to be equal to zero
    object = input() #enter the argument 

    for i in object:
        count=count+1

    print("Length of the string is"+str(count))

length(object)
查看更多
forever°为你锁心
5楼-- · 2019-01-26 02:41

It's a weird question so here's a weird answer!

try:
  for i in itertools.count(): mystring[i]
except IndexError:
  pass
查看更多
Anthone
6楼-- · 2019-01-26 02:43

Why you need to avoid the len function is beyond me, but strings are iterables. You should be able to do this:

strlen = 0

for c in myString:
  strlen += 1
查看更多
我命由我不由天
7楼-- · 2019-01-26 02: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
查看更多
登录 后发表回答