计算字符串中前导零的数量

jeo*_*eon 2 c#

我需要计算字符串中的前导零。

这就是我发现的整数前导零数

    static int LeadingZeros(int value)
{
   // Shift right unsigned to work with both positive and negative values
   var uValue = (uint) value;
   int leadingZeros = 0;
   while(uValue != 0)
   {
      uValue = uValue >> 1;
      leadingZeros++;
   }

   return (32 - leadingZeros);
}
Run Code Online (Sandbox Code Playgroud)

但找不到计算字符串中的前导零。

string xx = "000123";
Run Code Online (Sandbox Code Playgroud)

上面的例子有 000 所以我想得到结果计数为 3

我如何计算字符串中的零?

如果有人给我小费,非常感谢

dev*_*ter 6

最简单的方法是使用 LINQ :

var text = "000123";
var count = text.TakeWhile(c => c == '0').Count();
Run Code Online (Sandbox Code Playgroud)