开发者

String length without len function

开发者 https://www.devze.com 2023-01-21 01:29 出处:网络
Can anyone tell me how c开发者_如何学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.

Can anyone tell me how c开发者_如何学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.


>>> sum(map(lambda x:1, "hello world"))
11

>>> sum(1 for x in "foobar")
6

>>> from itertools import count
>>> zip(count(1), "baz")[-1][0]
3

A "tongue twister"

>>> sum(not out not in out for out in "shake it all about")
18

some recursive solutions

>>> def get_string_length(s):
...     return 1 + get_string_length(s[1:]) if s else 0
... 
>>> get_string_length("hello world")
11
>>> def get_string_length_gen(s):
...     yield 1 + next(get_string_length_gen(s[1:])) if s else 0
... 
>>> next(get_string_length_gen("hello world"))
11
>>> 


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.


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


Using while loop

a = 'string'
count = 0

while True:
    try:
        if a[count]:
            count += 1
    except IndexError as e:
        break

print(count)


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)


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

try:
  for i in itertools.count(): mystring[i]
except IndexError:
  pass


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


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


Try doing this, its pretty simple and easy

def calculate_length(a):
    x=0
    for i in a:
       x+=1
    print(x)


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


easy:

length=0
for x in "This is a string":
    length+=1
print(length)


Not very efficient but very concise:

def string_length(s):    
    if s == '': return 0
    return 1 + string_length(s[1:])


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.


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)


String length without using len function in python-

def strlen(myStr):
    if(myStr==""):
       return 0
    else:
       return 1+strlen(myStr[1:])


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.


Create a for loop

styx = "How do I count this without using len function"
number = 0
for c in styx:
   number = 0 + 1
print(number)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号