Question

I have product codes in the following format:

  1. 90004002
  2. 90004034
  3. 90012672

I need to remove the 90* characters until the first number that is not a zero, so the output should be:

  1. 4002
  2. 4034
  3. 12672

So what I do is first remove the leading 9 and then the zeros, I want to know if there's a simpler way of doing this, a one liner?

string productCode = skuid.ToString().TrimStart('9');
productCode = productCode.TrimStart('0');
Was it helpful?

Solution

or try regex:

x = Regex.Replace(x, "^90*", "");

OTHER TIPS

Well, you can write it like this:

string productCode = skuid.ToString().TrimStart('9').TrimStart('0');

But to be honest a regex would probably be cleaner here:

string productCode = Regex.Replace(skuid.ToString(), @"^90*", "");

You can use regular expressions for that

string input = "9000004002";
var output = Regex.Replace(input, @"^90*", ""); 

Why not....

string productCode = skuid.ToString().TrimStart('9', '0');

If 9000009002 is possible and should not be 2 but 9002:

string productCode = skuid.ToString().TrimStart('9').TrimStart('0');

You mentioned in the comments that skuid is an int. You should treat it as such:

private const int PRODUCT_OFFSET = 90000000;

public void DoStuff() {
    int skuid = 90012672;
    int productCode = GetProductCode(skuid);
}

private int GetProductCode(skuId) {
    return skuId - PRODUCT_OFFSET;
}

I need to remove the 90* characters until the first number that is not a zero

How about ignoring first 9 in your string then parsing it to int? Like;

string s = "9000004002";
int i = Int32.Parse(s.Substring(1));
Console.WriteLine(i.ToString()); //4002

I think this fits every case in your problem because parsing to int clears all leading zeros.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top