Search code examples
c#.netstring.net-2.0

How do I remove trailing digits fitting a pattern from a string in C#?


I have the following string: 0000015700

I need an algorithm that does the following:

  • goes to the first digit other than 0 from right to left (7, in this case)
  • extracts 6 digits starting from 7 going right to left (output would be 000157

It cannot be implemented using LINQ, since the project is running on the .NET 2.0 framework.

How do I do this in C#?


Solution

  • First you should trim end of string, and then get a required substring:

    var tmp = str.TrimEnd('0');
    var result = tmp.Substring(Math.Max(0,tmp.Length - 6));