Finding Out Length of a String Is very easy task . you can directly use inbuilt function like strlen() or len() .
But if there is restriction to not use these function then how find length of a string .
Length Using Loop : count number of element using for loop or while loop
But if there is restriction to not use these function then how find length of a string .
Length Using Loop : count number of element using for loop or while loop
- # Using For LOOP
- count=0
- st='http://beginer2cs.blogspot.com'
- for ch in st:
- count +=1
- print count
Length Using While LOOP :-
- # Using While Loop
- count=0
- st='http://beginer2cs.blogspot.com'
- while True:
- try: #to check Index out of range then break
- if st[count]:
- count +=1
- except:
- break
- print count
These two technique are very easy . But can you do it using Recursion (Try once)
Find length of string using Recursion :-
- def lenRecur(aStr):
- '''
- Recursive Way to Find Length of string
- '''
- if aStr == "":
- return 0
- else:
- return 1+lenRecur(aStr[0:-1])
- #1+ recursive_call(string with size less than current size)
- #In this case last char is dropped using slice
- if __name__=='__main__':
- st='http://beginer2cs.blogspot.com/'
- print lenRecur(st)
Comment your Query Below
Thank You !!
No comments:
Post a Comment
THANKS FOR UR GREAT COMMENT