Remove leading zeros

August 3, 2009 at 10:49
filed under Dynamics AX
Tagged , ,

Sometimes, you’ll want to add leading zeros, but other times, you’ll have to remove leading zeros from a string.
Here the code that does just that:

static void RemoveLeadingZeros(Args _args)
{
    str text = "0000A1337";
    ;

    while(substr(text, 1, 1) == "0")
    {
        text = substr(text, 2, strlen(text) - 1);
    }
    info(text);
}

The above example will work for any alphanumeric string.

When you’re sure you’re dealing with numeric strings, you can use this example:

static void RemoveLeadingZeros2(Args _args)
{
    str text = "00001337";
    ;

    if(strrem(text, "0123456789") == "")
        info(int2str(str2int(text)));
    else
        error("text is not numeric");
}

You should build in a check because the str2int() function doesn’t throw an error when the input isn’t numeric.

An example I found online also removes leading zeros from a string, but it fails if the first character after the zeros isn’t numeric:

static void RemoveLeadingZeros3(Args _args)
{
    str text = "0000A1337"; // doesnt work
    // str text = "00001A337"; // works
    ;

    info(strdel(text, 1, strfind(text, "123456789", 1, strlen(text)) - 1));
}

Conclusion:
The first example works best, but you should still be careful when converting the resulting string to other types, as you could get unexpected results.

no comments

RSS / trackback

respond