Home > Software design >  C# equivalent of Substring & Patindex of Sql server
C# equivalent of Substring & Patindex of Sql server

Time:10-30

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'

CodePudding user response:

  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.

CodePudding user response:

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"));
  • Related