187

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
0

9 Answers 9

384

This is the code you need:

string strInput = "0001234";
strInput = strInput.TrimStart('0');
4
  • 9
    problematic when strInput= "0000000"; or similar Feb 6, 2014 at 17:46
  • @Emjay because it will return an empty string instead of one zero. Nov 19, 2014 at 16:18
  • 29
    @avrahamcool it would still be doing exactly what it should. Returning a single zero would be an exception and should be handled by the developer.
    – user609926
    Dec 26, 2014 at 19:09
  • 20
    strInput.TrimStart('0').PadLeft(1, '0'); will handle "0000" > "0".
    – Chris Romp
    May 14, 2018 at 1:52
180

It really depends on how long the NVARCHAR is, as a few of the above (especially the ones that convert through IntXX) methods will not work for:

String s = "005780327584329067506780657065786378061754654532164953264952469215462934562914562194562149516249516294563219437859043758430587066748932647329814687194673219673294677438907385032758065763278963247982360675680570678407806473296472036454612945621946";

Something like this would

String s ="0000058757843950000120465875468465874567456745674000004000".TrimStart(new Char[] { '0' } );
// s = "58757843950000120465875468465874567456745674000004000"
3
  • 18
    problematic when strInput= "0000000"; or similar. because it will return an empty string instead of one zero. Nov 19, 2014 at 16:19
  • 2
    @avrahamcool which can be handled by looking at the length of the string and simply returning "0" if it's empty after the trim. Or using PadLeft(1, '0').
    – Cœur
    Aug 29, 2019 at 3:01
  • 1
    There's even a Wikipedia page on this en.wikipedia.org/wiki/Leading_zero. Interesting it says "A leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation.". i.e. removing leading zeros from "000" would give you "" not "0". I would say this is true especially if you are returning a string from the function (as mentioned the caller can handle the empty string and use zero if need be).
    – bytedev
    May 27, 2021 at 6:39
34

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";
3
  • 2
    let's assume that the string is very long, why trim it twice? you can save the trimmed string in a variable Nov 19, 2014 at 19:26
  • 2
    @avrahamcool, what do you mean, where is it trimmed twice? Thanks for the comment.
    – msysmilu
    Nov 29, 2017 at 12:45
  • ah, @avrahamcool, maybe that's why i edited it :) in the end it's a questions memory vs compute time; i guess today memory is not an issue anymore in these kinds of applications
    – msysmilu
    Dec 1, 2017 at 16:07
26

return numberString.TrimStart('0');

3
  • 5
    problematic when numberString= "0000000"; or similar Feb 6, 2014 at 17:47
  • 1
    @msysmilu because it will return an empty string instead of one zero. Nov 19, 2014 at 16:18
  • 1
    @avrahamcool You are right. Ergo i suggested an answer to avoid this
    – msysmilu
    Nov 19, 2014 at 18:49
7

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

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

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();
}
2
  • Perhaps overkill for the question as posed, this is the solution that I'm looking for as it also allows for the removal of right-padded zeroes for decimals. (Decimal.TryParse)
    – winwaed
    May 13, 2014 at 15:57
  • @JK I know the post is old but I really like this solution as it is clean and very easy to understand. Just one question changing the text in a key press event will also fire the textchanged event - am I correct ?
    – Ken
    Oct 19, 2016 at 16:00
4

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"
0
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");
2
  • 5
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
    – Nic3500
    Aug 26, 2018 at 16:24
  • Improved the answer as per suggestion from @Nic3500
    – Bharat
    Sep 3, 2018 at 20:49
-2

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.

3
  • Reinventing the weel is rarely a good option. Your code here is less readable and potentially more buggy than a simple string.TrimStart() Nov 7, 2022 at 12:00
  • Hi. There are just as many issues with TrimStart for this problem here, which I do use. It won't tell you how many were removed, so then you cannot then do new string with a char count. The point is to Replace, not Trim. A real alternative would be to do a for loop and count how many zeroes there are, TrimStart, then to do the new string with a char count. Thanks anyway.
    – Luke Nukem
    Nov 13, 2022 at 6:54
  • It is 2 years later, so my alternative might be what I convert my API to. Thanks again.
    – Luke Nukem
    Nov 13, 2022 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.