Posted By

Scooter on 09/06/08


Tagged

strings


Versions (?)

str_pad


 / Published in: ASP
 

URL: http://reusablecode.blogspot.com/2008/09/strpad.html

Pad a string to a certain length with another string. This has probably been the most reused function out of all I've ever written.

  1. <%
  2. ' Copyright (c) 2008, reusablecode.blogspot.com; some rights reserved.
  3. '
  4. ' This work is licensed under the Creative Commons Attribution License. To view
  5. ' a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or
  6. ' send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California
  7. ' 94305, USA.
  8.  
  9. Const STR_PAD_LEFT = "LEFT"
  10. Const STR_PAD_RIGHT = "RIGHT"
  11. Const STR_PAD_BOTH = "BOTH"
  12.  
  13. ' Pad a string to a certain length with another string.
  14. function str_pad(input, pad_length, pad_string, pad_type)
  15. dim output
  16. dim difference
  17.  
  18. output = ""
  19. difference = pad_length - len(input)
  20.  
  21. if difference > 0 then
  22. select case ucase(pad_type)
  23. case "LEFT"
  24. for i = 1 to difference step len(pad_string)
  25. output = output & pad_string
  26. next
  27.  
  28. output = right(output & input, pad_length)
  29. case "BOTH"
  30. output = input
  31.  
  32. for i = 1 to difference step len(pad_string) * 2
  33. output = pad_string & output & pad_string
  34. next
  35.  
  36. ' Not sure if it will step far enough when difference is an odd number, so this next block is just in case.
  37. if len(output) < pad_length then
  38. output = output & pad_string
  39. end if
  40.  
  41. output = left(output, pad_length)
  42. case else
  43. for i = 1 to difference step len(pad_string)
  44. output = output & pad_string
  45. next
  46.  
  47. output = left(input & output, pad_length)
  48. end select
  49. else
  50. output = input
  51. end if
  52.  
  53. str_pad = output
  54. end function
  55. %>

Report this snippet  

You need to login to post a comment.