djmattyg007

ComputerCraft Lua String Utils

Mar 23rd, 2024 (edited)
887
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.00 KB | Gaming | 0 0
  1. function string:contains(sub)
  2.     return self:find(sub, 1, true) ~= nil
  3. end
  4.  
  5. function string:startswith(start)
  6.     return self:sub(1, #start) == start
  7. end
  8.  
  9. function string:endswith(ending)
  10.     return ending == "" or self:sub(-#ending) == ending
  11. end
  12.  
  13. function string:replace(old, new)
  14.     local s = self
  15.     local searchStartIdx = 1
  16.  
  17.     while true do
  18.         local startIdx, endIdx = s:find(old, searchStartIdx, true)
  19.         if (not startIdx) then
  20.             break
  21.         end
  22.  
  23.         local postfix = s:sub(endIdx + 1)
  24.         s = s:sub(1, (startIdx - 1)) .. new .. postfix
  25.  
  26.         searchStartIdx = -1 * postfix:len()
  27.     end
  28.  
  29.     return s
  30. end
  31.  
  32. function string:insert(pos, text)
  33.     return self:sub(1, pos - 1) .. text .. self:sub(pos)
  34. end
  35.  
  36. local function lstrip_whitespace(s)
  37.     local _, pos = s:find("^%s+")
  38.     if pos then
  39.         s = s:sub(pos + 1)
  40.     end
  41.     return s
  42. end
  43.  
  44. local function rstrip_whitespace(s)
  45.     pos = s:find("%s+$")
  46.     if pos then
  47.         s = s:sub(1, pos - 1)
  48.     end
  49.     return s
  50. end
  51.  
  52. function string:strip()
  53.     local s = self
  54.     if s == "" then
  55.         return ""
  56.     end
  57.  
  58.     s = lstrip_whitespace(s)
  59.     s = rstrip_whitespace(s)
  60.  
  61.     return s
  62. end
  63.  
  64. function string:strip_prefix(prefix)
  65.     if prefix == nil then
  66.         return lstrip_whitespace(self)
  67.     end
  68.  
  69.     local s = self
  70.     local len = #s
  71.     local pLen = #prefix
  72.     if len == 0 or pLen == 0 or len < pLen then
  73.         return s
  74.     elseif s == prefix then
  75.         return ""
  76.     elseif s:sub(1, pLen) == prefix then
  77.         return s:sub(pLen + 1)
  78.     end
  79.  
  80.     return s
  81. end
  82.  
  83. function string:strip_suffix(suffix)
  84.     if suffix == nil then
  85.         return rstrip_whitespace(self)
  86.     end
  87.  
  88.     local s = self
  89.     local len = #s
  90.     local sLen = #suffix
  91.     if len == 0 or sLen == 0 or len < sLen then
  92.         return s
  93.     elseif s == suffix then
  94.         return ""
  95.     elseif s:sub(-sLen) == suffix then
  96.         return s:sub(1, len - sLen)
  97.     end
  98.  
  99.     return s
  100. end
Advertisement
Add Comment
Please, Sign In to add comment