【问题标题】:C#: Count Number of Digits in a String Using Do While LoopC#:使用 Do While 循环计算字符串中的位数
【发布时间】:2022-01-23 02:00:16
【问题描述】:

您好,如果您能帮助我修复此代码,我将不胜感激。我需要使用 Do While 循环。 我收到“超出范围”错误。 我相信我需要在某处减去或添加 1,但无法确定确切的位置。

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

提前谢谢你。

【问题讨论】:

  • 发生这种情况是因为您没有检查字符串是否足够长以在char.IsDigit(str[i]) 之前的索引i 处包含一个字符。
  • @user9938 不应该没问题,因为在检查while 条件之前它会增加i。但是,它 因空字符串而失败 (length==0)。但是您可以在do 循环之前或在do 循环中轻松检查,然后再获取字符。
  • 如果可以使用str.Length,那么使用循环计算str.Length的值是什么意思???
  • 我刚刚测试过,一切都很好,除了验证。
  • @Dominique 他们说使用 do/while 是“必需的”,所以我假设这是一项作业。

标签: c#


【解决方案1】:

由于do .. while 执行至少一次,你有一个空字符串特殊情况

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

【讨论】:

  • 非常感谢 Dmitry 先生,您的代码解决了这个问题。此外,我还学习了如何使代码更紧凑。非常感谢您和其他响应者的时间。
【解决方案2】:

你必须修复验证,你的例外是当字符串为空而不是空时

if (string.IsNullOrEmpty(str))
        throw new ArgumentNullException(nameof(str));

【讨论】:

  • 我相信这也能解决问题。无论如何,现在我明白问题所在了。谢谢
猜你喜欢
  • 1970-01-01
  • 2015-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 2021-01-31
  • 1970-01-01
相关资源
最近更新 更多