active92 active92 - 3 months ago 9
C# Question

Calculate number of zeros in a string

I have a string as follow

51200000000000000000000000000000


This string is not fixed. It will be appended depends on the number of boards. If there are two boards, the string will be as follow
5120000000000000000000000000000052200000000000000000000000000000


I would like to know how to calculate the number of zeros in the string.

I'm using the following code but it is not flexible if there are more than two boards.

string str = "51200000000000000000000000000000";
string zeros = "00000000000000000000000000000";
if (str.Contains(zeros))
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}

Answer

You can use the following piece of code to do this, which will give you the number of zeros(Example).

char matchChar='0';
string strInput = "51200000000000000000000000000000";
int zeroCount = strInput.Count(x => x == matchChar); // will be 29

You can do the same by iterating through each characters and check whether it is the required character(say 0) then take its count.

Comments