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:49

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.

查看更多
叛逆
3楼-- · 2019-01-26 02:54

easy:

length=0
for x in "This is a string":
    length+=1
print(length)
查看更多
劫难
4楼-- · 2019-01-26 02:55

I'm new to python but i would say that you can get the length of the string with a for loop, for example instead of:

> string=input("Enter a string")
> print(len(string))

do this:

>string=input("Enter a string")
>a=0
>for letter in string:
>a=a+1
>print(a)
查看更多
趁早两清
5楼-- · 2019-01-26 02:55
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.

查看更多
啃猪蹄的小仙女
6楼-- · 2019-01-26 02:56

Not very efficient but very concise:

def string_length(s):    
    if s == '': return 0
    return 1 + string_length(s[1:])
查看更多
别忘想泡老子
7楼-- · 2019-01-26 02:57

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
查看更多
登录 后发表回答