trim
Definition: |
object res = trim(object source,
object what=" \t\r\n",
bool return_index=false)
or ... object res = trim_head(object source, object what=" \t\r\n", bool return_index=false) -- or -- object res = trim_tail(object source, object what=" \t\r\n", bool return_index=false) |
Description: |
Trim whitespace from strings.
source: object (string) to be trimmed. what: elements (characters) to be removed. return_index: when true return {startpos,endpos} (trim), startpos (trim_head), or endpos (trim_tail) respectively. |
pwa/p2js: | Supported. |
Comments: |
Can theoretically be used for other purposes besides trimming whitespace, perhaps to trim unused entries from a table.
When return_index is true, the result is {startpos,endpos} (trim), startpos (trim_head), or endpos (trim_tail). To simplify processing, if source is not a sequence/string, but instead something like EOF (ie -1), it is returned unaltered. Note however that feature is certainly not intended for use when working with indexes (return_index=true), since treating the -1 (or whatever!) result as an index would probably be quite wrong! Instead it is usually easier to avoid the call when source is not a sequence, rather than struggle to interpret the result correctly. In other words, integer {s,e} = trim(5,x,true) will fail trying to extract {s,e} from 5, and likewise(-ish)
integer e = trim_head/tail(5,x,true) will succeed however some subsequent [5] usage will almost certainly fail.In both cases it is simply easier to avoid the call rather than test/ignore the bogus results. |
Example: |
?trim(" abc ") -- prints "abc" ?trim(`"abc"`) -- prints `"abc"` ?trim(`"abc"`,'\"') -- prints "abc" (not ""abc"" nor `"abc"`) ?trim(table,{{}}) -- removes s[i]={} entries from start and end (note the extra {}) ?trim(table,{{},0}) -- removes s[i]={} or 0 "" ?trim(gets(fn)) -- trim returns eof (-1) unaltered. |
Implementation: | See builtins\ptrim.e (an autoinclude) for details of the actual implementation. |