How to remove leading zeros using C#

前端 未结 8 1467
忘掉有多难
忘掉有多难 2020-12-01 04:16

How to remove leading zeros in strings using C#?

For example in the following numbers, I would like to remove all the leading zeros.

0001234
00000012         


        
相关标签:
8条回答
  • 2020-12-01 04:39

    It really depends on how long the NVARCHAR is, as a few of the above (especially the ones that convert through IntXX) methods will not work for:

    String s = "005780327584329067506780657065786378061754654532164953264952469215462934562914562194562149516249516294563219437859043758430587066748932647329814687194673219673294677438907385032758065763278963247982360675680570678407806473296472036454612945621946";
    

    Something like this would

    String s ="0000058757843950000120465875468465874567456745674000004000".TrimStart(new Char[] { '0' } );
    // s = "58757843950000120465875468465874567456745674000004000"
    
    0 讨论(0)
  • 2020-12-01 04:43
    Regex rx = new Regex(@"^0+(\d+)$");
    rx.Replace("0001234", @"$1"); // => "1234"
    rx.Replace("0001234000", @"$1"); // => "1234000"
    rx.Replace("000", @"$1"); // => "0" (TrimStart will convert this to "")
    
    // usage
    var outString = rx.Replace(inputString, @"$1");
    
    0 讨论(0)
提交回复
热议问题