How do you trim leading zeros from a string in C#?

By On

I have a numeric string that contains leading zeros that I want to remove before I perform any comparisons with it on other objects. How can I trim an undefined number of zeros from a string without having to loop through the characters in the string and remove all the zeros that come first?


1 Answer

- Advertisment -
Answered By Dan On

The trim method has an option argument to pass an array of chars you want to trim. By default it will just remove all whitespace from the string. If you pass the char array, it will remove all of those characters in the same way that it would with the whitespace. the following code will remove leading zeros

var no zeros = string.TrimStart(new char[] { '0' })))