无法在 TryParse 中使用 SUBSTRING

发布于 2024-11-02 04:09:20 字数 675 浏览 2 评论 0原文

我在我的代码中发现一个错误,其中子字符串不起作用,它说“startIndex不能大于字符串的长度”

 static int MyIntegerParse(string possibleInt)
    {
        int i;
        return int.TryParse(possibleInt.Substring(2), out i) ? i : 0;        
    }

我在这里使用了该过程:

var parsed = File.ReadLines(filename)
            .Select(line => line.Split(' ')     
                .Select(MyIntegerParse)
                .ToArray())
            .ToArray();

但我不明白为什么它是错误的,因为我之前已经使用过子字符串这是工作,我可以在这里寻求帮助吗? thnaks。

示例字符串:

10192 20351 30473 40499 50449 60234 
10192 20207 30206 40203 50205 60226 
10192 20252 30312 40376 50334 60252

I found an error in my code, where the subtring is not work, it says "startIndex cannot be larger than the length of string"

 static int MyIntegerParse(string possibleInt)
    {
        int i;
        return int.TryParse(possibleInt.Substring(2), out i) ? i : 0;        
    }

I used the procedure here:

var parsed = File.ReadLines(filename)
            .Select(line => line.Split(' ')     
                .Select(MyIntegerParse)
                .ToArray())
            .ToArray();

But I don't understand why it's error because I already used the substring before and it's work, can I ask for a help here? thnaks.

sample string:

10192 20351 30473 40499 50449 60234 
10192 20207 30206 40203 50205 60226 
10192 20252 30312 40376 50334 60252

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

尝蛊 2024-11-09 04:09:20

possibleInt 包含的字符少于两个时,Substring 将失败,因此您也应该将该测试添加到您的代码中。我怀疑您的 Split 调用在某些情况下会产生空字符串。这个空字符串被传递到 int 解析器中,然后在 Substring 调用上失败。因此,您可能应该做两件事:

  • 在拆分中摆脱空字符串
  • 在解析代码中故意处理短字符串或空字符串

摆脱空字符串非常简单:

var parsed = File.ReadLines(filename)
            .Select(line => line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(MyIntegerParse)
                .ToArray())
            .ToArray();

可以像这样添加对空字符串的故意处理:

static int MyIntegerParse(string possibleInt)
{
    if (string.IsNullOrEmpty(possibleInt) || possibleInt.Length < 2)
    { 
        return 0;
    }

    int i;
    return int.TryParse(possibleInt.Substring(2), out i) ? i : 0;        
}

..或者,如果您喜欢紧凑且难以阅读的结构:

static int MyIntegerParse(string possibleInt)
{
    int i;
    return (!string.IsNullOrEmpty(possibleInt) 
        && possibleInt.Length >= 2
        && int.TryParse(possibleInt.Substring(2), out i)) ? i : 0;        
}

不,我选择在收到太短的字符串时返回 0。在您的情况下,返回其他值、引发异常或使用 Debug.Assert 语句可能更有意义。

Substring will fail when possibleInt contains fewer than two characters, so you should add that test to your code as well. I suspect that you Split call produces an empty string during some circumstances. This empty string is passed into your int-parser which then fails on the Substring call. So, you should probably do two things:

  • Get rid of empty strings in the splitting
  • Handle short or empty strings deliberately in your parsing code

Getting rid of empty strings is quite easy:

var parsed = File.ReadLines(filename)
            .Select(line => line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(MyIntegerParse)
                .ToArray())
            .ToArray();

Adding deliberate handling of empty strings can be done like so:

static int MyIntegerParse(string possibleInt)
{
    if (string.IsNullOrEmpty(possibleInt) || possibleInt.Length < 2)
    { 
        return 0;
    }

    int i;
    return int.TryParse(possibleInt.Substring(2), out i) ? i : 0;        
}

...or if you are a fan of compact and hard-to-read constructs:

static int MyIntegerParse(string possibleInt)
{
    int i;
    return (!string.IsNullOrEmpty(possibleInt) 
        && possibleInt.Length >= 2
        && int.TryParse(possibleInt.Substring(2), out i)) ? i : 0;        
}

No, I have chosen to return 0 when I get strings that are too short. In your case it might make more sense to return some other value, throw an exception or use a Debug.Assert statement.

还不是爱你 2024-11-09 04:09:20

possibleInt 字符串的长度至少需要两个字符。如果不是,您将看到您所描述的错误。

The possibleInt string needs to be at least two characters long. When it isn't then you'll see the error that you've described.

眸中客 2024-11-09 04:09:20

在 return 语句之前添加此内容,看看是否可以帮助您弄清楚发生了什么:

Debug.Assert(!string.IsNullOrEmpty(possibleInt) && possibleInt.Length > 2);

在调试模式下运行时,如果不满足上述两种情况,则会抛出异常。

您还可以使用代码合同,如下所示:

Contract.Assert(!string.IsNullOrEmpty(possibleInt) && possibleInt.Length > 2);

Add this before your return statement and see if that helps you figure out what's going on:

Debug.Assert(!string.IsNullOrEmpty(possibleInt) && possibleInt.Length > 2);

When running in Debug mode this will throw an exception if the two cases above are not met.

You could also use a Code Contract like this:

Contract.Assert(!string.IsNullOrEmpty(possibleInt) && possibleInt.Length > 2);
靑春怀旧 2024-11-09 04:09:20

您收到此异常是因为您试图获取从大于字符串长度的索引开始的字符串的子字符串。

someString.Substring(x) 将为您提供 someString 的子字符串,从字符串中的位置 x 开始,并且它是从零开始的。您收到此异常是因为在本例中 2 超出了特定字符串长度的范围。

在其周围放置一个 try catch 或一个断点,您将看到导致此异常的字符串的长度小于 3。

You are getting this exception because you are trying to get the substring of a string starting at an index that is greater than the length of the string.

someString.Substring(x) will give you the substring of someString starting at position x in the string, and it is zero based. You are getting this exception because in this case 2 is outside the range of the particular strings length.

Stick a try catch around it, or a breakpoint and you will see the string that is causing this exception has a length less than 3.

风向决定发型 2024-11-09 04:09:20

您尝试解析的行并没有那么长。根据 Substring 上的 C# 规范:

The zero-based starting character position of a substring in this instance. 

您传入的字符串有其中有 0 或 1 个字符。您需要修改代码来处理这种情况。

编辑:此外,您应该使用 split 的重载从文件中删除空元素:

.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntires)

The line you are attempting to parse is not that long. From the C# Specification on Substring:

The zero-based starting character position of a substring in this instance. 

The string you are passing in either has 0 or 1 characters in it. You need to modify your code to handle such a situation.

EDIT: Additionally, you should be removing empty elements from your file using an overload of split:

.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntires)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文