Kevin Kevin - 4 years ago 127
C# Question

Is there a way to trim leading characters using String.Format()?

Need to know of there is a way to use String.Format to remove leading characters from a string. I have a limitation in some existing code that I can only pass in a string and a format string for it.

So can you do something like

String.Format("Test output: {0:#}","001")


and produce the output


"Test output: 1"


I think the answer is 'No' but I wanted to make sure.

EDIT: To clarify, the format string will be put in a configuration file and the string to be formatted is a value coming out of a database. I can't execute any code on it. Has to be through the format string.

Answer Source

You could do it on the arg you are passing

String.Format("Test output: {0:#}", "001".TrimStart('0'))

Alternatively you could probably do a find with replace using a regular expression on the resulting string.


An other alternative is to define and pass in your own formatter using a custom implementation of IFormatProvider. I am not sure if this is allowed or not based your your last edit.


However, based on the restrictions listed, there is no way to do it with just the format string input

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download