How to check if there is only one time zero in a string with C#

1 Answer

0 votes
using System;

public class Program 
{
	private static bool OnlyOneZero(string str) {
		int count = 0;

		foreach (char ch in str.ToCharArray()) {
			if (ch == '0') {
				count++;
			}
		}

		return count == 1;
	}

	public static void Main(string[] args)
	{
		const string s1 = "294098";
		Console.WriteLine(OnlyOneZero(s1) ? "yes" : "no");

		const string s2 = "47034099";
		Console.WriteLine(OnlyOneZero(s2) ? "yes" : "no");
	}
}





/*
run:
  
yes
no
  
*/

 



answered Apr 11, 2023 by avibootz

Related questions

...