Thursday 25 September 2014

Length of string using Recursion

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

  1. # Using For LOOP
  2. count=0
  3. st='http://beginer2cs.blogspot.com'
  4. for ch in st:
  5.     count +=1
  6. print count


Length Using While LOOP :-


  1. # Using While Loop
  2. count=0
  3. st='http://beginer2cs.blogspot.com'
  4. while True:
  5.     try#to check Index out of range then break
  6.         if st[count]:
  7.             count +=1
  8.     except:
  9.         break
  10. print count

These two technique are very easy . But can you do it using Recursion (Try once)

Find length of string using Recursion :-


  1. def lenRecur(aStr):
  2.     '''
  3.      Recursive Way to Find Length of string
  4.    '''
  5.     if aStr == "":
  6.         return 0
  7.     else:
  8.         return 1+lenRecur(aStr[0:-1])
  9.              #1+ recursive_call(string with size less than current size)
  10.              #In this case last char is dropped using slice
  11. if __name__=='__main__':
  12.     st='http://beginer2cs.blogspot.com/'
  13.     print lenRecur(st)

Comment your Query Below
Thank You !!

No comments:

Post a Comment

THANKS FOR UR GREAT COMMENT

Blogger Widgets