ตุลาคม 04, 2558

Lab5_strings

def setup():
   print(my_count("Thailand","a"))
   print(my_find("Thailand","i"))
   print(my_replace("Thailand","land","thai"))
   print(my_strip("Thailand     "))
   print(my_startswith("Thailand","Sun"))
   print(my_endswith("Thailand","and"))
 
def my_count(full,part):
   count = 0
   i = 0
   while(i<len(full)):
      if(full[i] == part):
         count = count+1
      i = i+1
   return count

def my_find(full,part):
   i = 0
   while(i<len(full)):
      if(full[i] == part):
         index = i
         break
      i = i+1
   return index

def my_replace(full,old,new):
   newStr = ""
   l = len(old)
   i = 0
   while(i<len(full)):
      a = full[i]
      j = 1
      while(j<l and i+j<len(full)):
         a = a+full[i+j]
         j = j+1
      if(a == old):
         newStr = newStr+new
         i = i+(l-1)
      else:
         newStr = newStr+full[i]
      i = i+1
   return newStr

def my_strip(full):
   newStr = ""
   i = 0
   while(i<len(full)):
      if(full[i] != ' '):
         start = i
         break
      i = i+1
   i = len(full)-1
   while(i>=0):
      if(full[i] != ' '):
         end = i
         break
      i = i-1
   j = start
   while(j<=end):
      newStr = newStr+full[j]
      j = j+1
   return newStr
 
def my_startswith(full,start):
   result = True
   l = len(start)
   i = 0
   while(i<l):
      if(full[i] != start[i]):
         result = False
         break
      i = i+1
   return result
 
def my_endswith(full,end):
   result = True
   l = len(end)
   i = len(full)-l
   j = 0
   while(i<len(full)):
      if(full[i] != end[j]):
         result = False
         break
      j = j+1
      i = i+1
   return result

setup()

ไม่มีความคิดเห็น:

แสดงความคิดเห็น