Lia
Lia

Reputation: 526

Remove leading zeroes but not all zeroes in C#

I have the string value 000001 and need to get the last three digits - 001

Zeroes quantity before 001 can be different and the value itself can be 011 or 111

     Value   Expected Value
       000   000
      0001   001
     00011   011
    000111   111
   0001111   Not a case

There is a way to remove all leading zeros value.TrimStart('0') but how to keep zeros that are in scope of the last three chars?

Is there a way to trim till specified chars left?

Upvotes: 1

Views: 872

Answers (3)

Caius Jard
Caius Jard

Reputation: 74605

In modern C# we have quite a nice way of expressing parts of a string with indexes and ranges

value[^3..];

It means "3 from the end, to the end, of value".

Your question was a bit confusing; you seem to say that your value will always have more than 3 digits so this will be safe to do.. If it won't always have more than 3 digits you could either PadLeft it first, or, more compactly, concat your value onto "00" (assuming you'll always have a digit)

value.PadLeft(3,'0')[^3..];

("00"+value)[^3..];

Upvotes: 2

Ravi Tiwari
Ravi Tiwari

Reputation: 962

Since you need last three characters, extracting will do.

string value = "12345"; // "0012";
Console.WriteLine(value.Substring(value.Length - 3));

Upvotes: 4

D Stanley
D Stanley

Reputation: 152521

Do a trim followed by a PadLeft:

value.TrimStart('0').PadLeft(3,'0')

Upvotes: 9

Related Questions