指数超出范围。必须是非负且小于c#中集合的大小 [英] index was out of range. must be nonnegative and less than the size of the collection in c#

查看:49
本文介绍了指数超出范围。必须是非负且小于c#中集合的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此错误索引超出范围。必须是非负且小于c中的集合大小#

参数:index



有谁可以帮我这个?



I'm getting this error index was out of range. must be nonnegative and less than the size of the collection in c#
parameter: index

Can anyone help me with this?

private static string GetTxtBtwn(string input, string start, string end, int startIndex, bool UseLastIndexOf)
        {
            int index1 = UseLastIndexOf ? input.LastIndexOf(start, startIndex) :
                                          input.IndexOf(start, startIndex);
            if (index1 == -1) return "";
            index1 += start.Length;
            int index2 = input.IndexOf(end, index1);
            if (index2 == -1) return input.Substring(index1);
            return input.Substring(index1, index2 - index1);

            
        }

推荐答案

究竟为什么取决于您的数据,但获取的机制问题很简单:

如果在开始之前找到结束,或者作为起始字符串的一部分,会发生什么?

即如果输入为1234567890且start为345678且结束为23,则

Exactly why is up to your data, but the mechanics of getting the problem are simple:
What happens if the end is found before the start, or as part of the start string?
I.e. if input is "1234567890" and start is "345678" and end is "23", then
index1 == 8
index2 == 1

所以你的长度是负数。这不会导致你这次得到的确切错误,但它是失败之路的一个例子,它依赖于你的数据来确切地解决问题所在。



如果遇到这样的问题,请使用调试器,然后查看数据。逐行逐步,尝试找出什么值是什么。

So your length will be negative. That won't cause the exact error you are getting this time, but it's an example of a "route to failure" which depends on your data to work out exactly what the problem is.

If you get a problem like this, use the debugger, and look at your data. Step through line by line and try to spot what values are what.


虽然我不同意OriginalGriff的分析,但是你开始搜索结束后的第二个子字符串。第一个字符串,所以他的断言不应该发生,我同意他的陈述:取决于你的数据所以使用调试器。



你确定你提供的参数startindex方法是不是超过了字符串的结尾?这会在查找index1的行中抛出此错误。
Allthough I do not agree with the analysis of OriginalGriff, you are starting your search for the second substring after the end of the first string so his assertion should not happen, i do agree with his statement: depends on your data so use the debugger.

Are you sure the parameter startindex you are providing to the method is not past the end of the string? That would throw this error at the line looking for your index1.


这篇关于指数超出范围。必须是非负且小于c#中集合的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆