0

I have the following SQL Server code which I would like to do in C# code. The logic is - to remove leading zeros please help me to translate the code into C#.


DECLARE @TESTVariable as varchar(500)
Set @TESTVariable = '00013025990'

SELECT Substring(@TESTVariable, Patindex('%[^0 ]%', @TESTVariable + ' '), Len(@TESTVariable))



output expected

input output
'001' '1'
'00' '0'
'00013025990' '13025990'
2
  • str.TrimStart('0') Commented Oct 29, 2022 at 14:59
  • Look at TrimStart. Again, if there are only zeros it will return empty, so add a check for it in your code TrimStart('0') Commented Oct 29, 2022 at 15:00

2 Answers 2

3
  1. String.TrimStart(Char) method is used to remove specified character from leading edge of the current string.

     string s= "00013025990";
     var result = s.TrimStart('0');
    
  2. or convert the string to a number so that the zeros are removed from the beginning (this method is correct for the zero character only)

    var result=int.Parse(s); 
    

If you want to get '0' from '00', the TrimStart is not correct and you have to use the second way.

Sign up to request clarification or add additional context in comments.

Comments

2

Rather than convert the T-SQL code directly to roughly .NET equivalents, consider using the String.TrimStart method for this task.

var TESTVariable = "00013025990";
Console.WriteLine(TESTVariable.TrimStart('0'));

I see from your edit you may have a zero value you want to preserve. If the string values are integers, you can use Parse and ToString to remove leading zeros except for the last:

Console.WriteLine(Int64.Parse("001").ToString("0"));
Console.WriteLine(Int64.Parse("00").ToString("0"));
Console.WriteLine(Int64.Parse("00013025990").ToString("0"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.