简体   繁体   中英

C# equivalent of Substring & Patindex of Sql server

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'

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"));
  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM