Thursday, April 29, 2010

How to remove leading characters, like zeros, in a string

Ax comes with lots of functions to operate on strings. Like substr, strfind, strscan, strlen, strIns, strLTrim, ...
But it looks like there is always room for more...

This post is about the trimming of strings. Unfortunately, strLTrim (and strRTrim) aren't that flexible. You can only remove leading (or trailing) blanks with these functions, no other characters.

Say you have to remove the leading zeros in a string (an amount you get in string format, a VAT num, bank account number, ...), you are out of luck. You could write your own little function to perform this task, or... use CLRInterop.

You can fall back to the use of TrimStart from System.String. With TrimStart, you can remove all leading occurrences of a set of characters specified in the parameters.

Example

System.String myString2Trim="0000123-456-000-789";
System.String trimChars="0";
;
info(myString2Trim.TrimStart(trimChars.ToCharArray()));


With this, you can remove any leading characters you wish. (Think of spaces, dots, ...)
So if you want your own version of strLTrim from Ax:

System.String myString2Trim=" 123-456-000-789";
System.String trimChars=" ";
;
info(myString2Trim.TrimStart(trimChars.ToCharArray()));


As a complementary function, there is also TrimEnd to remove any trailing occurrences of some specified characters.

(Note: Maybe you use a shortcut like int2str(str2int("001001")) to remove leading zeros from a string. That's OK, as long as you realise this has it's limitations.)

No comments:

Post a Comment