Here are the different ways to trim a string in Corona SDK.


-- CoderzHeaven String Trimming examples in Corona.
-- Here you can see different methods for trimming a string in corona.

function trim1(s)
  return (s:gsub("^%s*(.-)%s*$", "%1"))
end

function trim2(s)
  return s:match "^%s*(.-)%s*$"
end

function trim3(s)
  return s:gsub("^%s+", ""):gsub("%s+$", "")
end

function trim4(s)
  return s:match"^%s*(.*)":match"(.-)%s*$"
end

function trim5(s)
  return s:match'^%s*(.*%S)' or ''
end

-- has bad performance.. use at your own risk.
function trim6(s)
  return s:match'^()%s*$' and '' or s:match'^%s*(.*%S)'
end

local str = " CoderzHeaven ";
print("--------------Trimming a string in Corona SDK---------------");
print ('Str Original Length Length : '..string.len(str))

str = trim1(str);
print ('Str Length using First Function  : '..string.len(str))

-- reassigning to check trim function using other functions.
str = " CoderzHeaven ";
str = trim2(str);
print ('Str Length using second function : '..string.len(str))

str = " CoderzHeaven ";
str = trim3(str);
print ('Str Length using third function  : '..string.len(str))

Please check the console for the output.

Download the source code from here

 

Leave a Reply

Your email address will not be published. Required fields are marked *

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.