How to remove leading zeros using C#

C#String

C# Problem Overview


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

C# Solutions


Solution 1 - C#

This is the code you need:

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

Solution 2 - C#

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"

Solution 3 - C#

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";

Solution 4 - C#

return numberString.TrimStart('0');

Solution 5 - C#

http://msdn.microsoft.com/en-us/library/f02979c7.aspx">TryParse</a> works if your number is less than http://msdn.microsoft.com/en-us/library/system.int32.maxvalue.aspx">Int32.MaxValue</a>;. This also gives you the opportunity to handle badly formatted strings. Works the same for http://msdn.microsoft.com/en-us/library/system.int64.maxvalue.aspx">Int64.MaxValue</a> and http://msdn.microsoft.com/en-us/library/system.int64.tryparse.aspx">Int64.TryParse</a>;.

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

Solution 6 - C#

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

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

Solution 7 - C#

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"

Solution 8 - C#

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");

Solution 9 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser874966View Question on Stackoverflow
Solution 1 - C#Craig HannonView Answer on Stackoverflow
Solution 2 - C#Master StrokeView Answer on Stackoverflow
Solution 3 - C#msysmiluView Answer on Stackoverflow
Solution 4 - C#RayView Answer on Stackoverflow
Solution 5 - C#JK.View Answer on Stackoverflow
Solution 6 - C#Deependra MishraView Answer on Stackoverflow
Solution 7 - C#dNPView Answer on Stackoverflow
Solution 8 - C#BharatView Answer on Stackoverflow
Solution 9 - C#Luke NukemView Answer on Stackoverflow