[c#] How to remove leading zeros using C#

How to remove leading zeros in strings using C#?

For example in the following numbers, I would like to remove all the leading zeros.

0001234
0000001234
00001234

This question is related to c# string

The answer is


Code to avoid returning an empty string ( when input is like "00000").

string myStr = "00012345";
myStr = myStr.TrimStart('0');
myStr = myStr.Length > 0 ? myStr : "0";

return numberString.TrimStart('0');


Regex rx = new Regex(@"^0+(\d+)$");
rx.Replace("0001234", @"$1"); // => "1234"
rx.Replace("0001234000", @"$1"); // => "1234000"
rx.Replace("000", @"$1"); // => "0" (TrimStart will convert this to "")

// usage
var outString = rx.Replace(inputString, @"$1");

I just crafted this as I needed a good, simple way.

If it gets to the final digit, and if it is a zero, it will stay.

You could also use a foreach loop instead for super long strings.

I just replace each leading oldChar with the newChar.


This is great for a problem I just solved, after formatting an int into a string.

    /* Like this: */
    int counterMax = 1000;
    int counter = ...;
    string counterString = counter.ToString($"D{counterMax.ToString().Length}");
    counterString = RemoveLeadingChars('0', ' ', counterString);
    string fullCounter = $"({counterString}/{counterMax})";
    // = (   1/1000) ... ( 430/1000) ... (1000/1000)

    static string RemoveLeadingChars(char oldChar, char newChar, char[] chars)
    {
        string result = "";
        bool stop = false;
        for (int i = 0; i < chars.Length; i++)
        {
            if (i == (chars.Length - 1)) stop = true;
            if (!stop && chars[i] == oldChar) chars[i] = newChar;
            else stop = true;
            result += chars[i];
        }
        return result;
    }

    static string RemoveLeadingChars(char oldChar, char newChar, string text)
    {
        return RemoveLeadingChars(oldChar, newChar, text.ToCharArray());
    }

I always tend to make my functions suitable for my own library, so there are options.


TryParse works if your number is less than Int32.MaxValue. This also gives you the opportunity to handle badly formatted strings. Works the same for Int64.MaxValue and Int64.TryParse.

int number;
if(Int32.TryParse(nvarchar, out number))
{
   // etc...
   number.ToString();
}

Using the following will return a single 0 when input is all 0.

string s = "0000000"
s = int.Parse(s).ToString();

This is the code you need:

string strInput = "0001234";
strInput = strInput.TrimStart('0');

This Regex let you avoid wrong result with digits which consits only from zeroes "0000" and work on digits of any length:

using System.Text.RegularExpressions;

/*
00123 => 123
00000 => 0
00000a => 0a
00001a => 1a
00001a => 1a
0000132423423424565443546546356546454654633333a => 132423423424565443546546356546454654633333a
*/

Regex removeLeadingZeroesReg = new Regex(@"^0+(?=\d)");
var strs = new string[]
{
    "00123",
    "00000",
    "00000a",
    "00001a",
    "00001a",
    "0000132423423424565443546546356546454654633333a",
};
foreach (string str in strs)
{
    Debug.Print(string.Format("{0} => {1}", str, removeLeadingZeroesReg.Replace(str, "")));
}

And this regex will remove leading zeroes anywhere inside string:

new Regex(@"(?<!\d)0+(?=\d)");
//  "0000123432 d=0 p=002 3?0574 m=600"
//     => "123432 d=0 p=2 3?574 m=600"