c#字符串toCharArray超出范围异常

本文关键字:范围 异常 字符串 toCharArray | 更新日期: 2023-09-27 18:11:39

我在修复别人的代码时遇到了这个问题。显然,他们试图控制小数点后的数字,像这样:

public static bool check_count(double d)
    {
        string str = d.ToString();
        bool b = true;
        if (str.IndexOf('.'))
        {
            char[] ch = str.ToCharArray(str.IndexOf('.'), str.Length - 1);
            if (ch.Length > 5)
                b = false;
        }
        return b;
    }

我不打算麻烦自己修复,因为我用正则表达式代替它,但它让我很好奇。当ToCharArray不应该抛出ArgumentOutOfRangeException时(?!)

比如说

string str = "20.222";
Console.WriteLine(str);
int index = str.IndexOf('.');
if (index > -1)
{
   Console.WriteLine(index);
   Console.WriteLine(str.Length-1);
   char[] ch = str.ToCharArray(index, str.Length - 1);
}
输出:

20.222
2
5

现场演示[here]

所以字符串是6个字符长,开始索引是2,哪个参数超出了什么范围?

我感到迷失在这…什么好主意吗?

谢谢

c#字符串toCharArray超出范围异常

哪个参数超出了什么范围?

好吧,我希望异常能告诉你——但我也希望它是第二个参数。(编辑:看看你实际上得到的例外,甚至从。net,它实际上是指责第一个参数。不可否认,第一个参数和第二个参数的组合是无效的,但在这种情况下,更明智的做法是指责第二个参数,因为第一个参数本身是有效的。

查看文档-第二个参数是长度,而不是结束索引。所以我猜你想要这样的:

char[] ch = str.ToCharArray(index, str.Length - index);

或者在之后只得到数字 .:

char[] ch = str.ToCharArray(index + 1, str.Length - index - 1);