问题:-index和length必须引用字符串中的位置。 c#中的参数名称长度 [英] problem :-index and length must refer to a location within the string. parameter name length in c#

查看:121
本文介绍了问题:-index和length必须引用字符串中的位置。 c#中的参数名称长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码: -

string p =123456789;

p.substring(0,8);

问题:-index和length必须引用字符串中的位置。参数名称长度在c#中,字符串没有固定长度取决于用户,当字符串小于8时会产生错误,当字符串长度大于8时它工作正常

解决方案

您需要做的就是:1)避免硬编码立即常量(例如8); 2)在某些情况下,检查字符串的长度(类似地,集合的元素数,数组的长度等)



即使起始索引是0,仍然需要进行一些检查,因为索引0处的元素对于空字符串不存在。至于 string.Substring 中使用的长度,您可以使用以下功能:您的长度可以超过子串的可用部分的实际长度;在这种情况下,结果将被截断为可用长度。



这在文档中没有明确说明: https://msdn.microsoft.com/en-us/library/aka44szs%28v=vs.110%29.aspx [ ^ ]。



然而,隐含地,这表明了。查看文档的异常部分:仅抛出与错误索引值相关的异常;这意味着第二个参数的值太大,我会按照我解释的方式来容忍。



-SA

记住它是基于ZERO的索引而不是基于。



当字符串长8位数时,0,7是第8位数。



字符串:

12345678



索引:

01234567

code:-
string p = "123456789";
p.substring(0,8);

problem :-index and length must refer to a location within the string. parameter name length in c# , string does not have fixed length depend on user, when string less than 8 it create error, when string length is more than 8 it work fine

解决方案

All you need to do is: 1) avoid hard-coding immediate constants (such as 8); 2) in some cases, check up the length of the string (similarly, element count of collection, length of arrays, etc.)

Even if the starting index is 0, some check is still needed, because the element at the index 0 does not exist for an empty string. As to the length used in string.Substring, you can use the following feature: your length can exceed actual length of available part of sub-string; in this case, result will be truncated to available length.

This is not explicitly explained in the documentation: https://msdn.microsoft.com/en-us/library/aka44szs%28v=vs.110%29.aspx[^].

However, implicitly, this is indicated. Look at the exception part of the documentation: only the exception related to wrong index value is thrown; it means that too big value for the second parameter will be tolerated the way I explained.

—SA


Remember it is ZERO based index not ONE based.

When string is 8 digits long then 0,7 is the 8th digit.

String:
12345678

Index:
01234567


这篇关于问题:-index和length必须引用字符串中的位置。 c#中的参数名称长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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