简体   繁体   English

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

[英]count leading number of zeros in string

i need to count leading zeros in string.我需要计算字符串中的前导零。

this is what i found count leading zeros in integer这就是我发现在整数中计数前导零的结果

    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);
}

but couldn't found counting leading zeros in string.但找不到计算字符串中的前导零。

string xx = "000123";

above example have 000 so i want to get result count number as 3上面的例子有 000 所以我想得到结果计数为 3

how i can count zeros in string?我如何计算字符串中的零?

if anyone tip for me much appreciate如果有人给我小费,非常感谢

The Simplest approach is using LINQ :最简单的方法是使用 LINQ :

var text = "000123";
var count = text.TakeWhile(c => c == '0').Count();

int can't have leading 0 's, however I assume you just want to count leading zeros in a string. int不能有前导0 ,但是我假设您只想计算字符串中的前导零。

Without getting fancy, just use a vanilla for loop:不要花哨,只需使用香草for循环:

var input = "0000234";
var count = 0;

for(var i = 0; i < input.Length && input[i] == '0'; i++)
   count++;

Full Demo Here完整演示在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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