Denys Wessels
Denys Wessels

Reputation: 17049

Remove characters from a string C#

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

Upvotes: 1

Views: 247

Answers (6)

CodingIntrigue
CodingIntrigue

Reputation: 78605

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

Upvotes: 4

Soner Gönül
Soner Gönül

Reputation: 98868

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.

Upvotes: 3

Tim Schmelter
Tim Schmelter

Reputation: 460370

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

Upvotes: 4

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28588

or try regex:

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

Upvotes: 8

Szymon
Szymon

Reputation: 43023

You can use regular expressions for that

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

Upvotes: 4

David Heffernan
David Heffernan

Reputation: 613612

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

Upvotes: 4

Related Questions