Hi I would appreciate if you could help me to fix this code. I am required to use Do While Loop. I am receiving "Outside Bound" error. I believe I need to substract or add 1 somewhere but can't figure out exactly where.
public static int Digit(string str)
{
if (str is null)
{
throw new ArgumentNullException(nameof(str));
}
int count = 0;
int i = 0;
do
{
if (char.IsDigit(str[i]))
{
count ;
}
i ;
}
while (i < str.Length);
return count;
}
Thank you in advance.
CodePudding user response:
you have to fix validation, you exception was when string was empty, but not null
if (string.IsNullOrEmpty(str))
throw new ArgumentNullException(nameof(str));
CodePudding user response:
Since do .. while
executes at least once, you have a special case for an empty string:
public static int Digit(string str)
{
if (str is null)
throw new ArgumentNullException(nameof(str));
if (string.IsNullOrEmpty(str))
return 0;
int count = 0;
int i = 0;
do
{
if (char.IsDigit(str[i ])) // Let's make it compact
count ;
}
while (i < str.Length);
return count;
}