索引和计数必须引用字符串中的位置。 [英] Index and count must refer to a location within the string.?

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

问题描述

Hii,



我想从我的字符串中删除前2个字符..



但它的抛出索引和计数必须引用字符串中的位置。错误



lblDataForYear.Text = expYear.ToString()+/+(expYear + 1).ToString()。Remove(0,2);

Hii ,

I am trying to remove first 2 char from my string ..

But its throwing Index and count must refer to a location within the string. error

lblDataForYear.Text = expYear.ToString() + "/" + (expYear + 1).ToString().Remove(0,2);

推荐答案





假设expYear是数字类型且有4位数,请尝试这样:





Hi,

Assuming that expYear is numeric type and has 4 digits try this way:


lblDataForYear.Text = string.Format("{0}/{1}", expYear, (expYear + 1).ToString().Substring(2, 2));





干杯!



Cheers!


从异常消息中可以清楚地看到实际错误即将来临从您调用String的 .Remove()方法。您传递的参数必须有效,我的意思是字符串中的字符总数必须足以使此函数可用。据我所知,expYear是一个空字符串或只包含一个字符。我有一个此问题的示例,其中显示此错误消息,因为该字符串只包含一个字符。 https://dotnetfiddle.net/DTspxj [ ^ ]



It is clear from the exception message that the actual error is coming from the .Remove() method you're calling on the String. The parameters that you're passing must be valid, I mean that the total number of the characters in your string must be enough for this function to work on. As far as I know the expYear is either an empty string or it contains only one character. I have an example of this problem, where this error message is shown because the string contained only one character. https://dotnetfiddle.net/DTspxj[^]

// variable
int year = 1;
// write the string without first two characters
Console.WriteLine(year.ToString().Remove(0, 2));
// but error! Index and count must refer to a location within the string.





但是这第二个代码,即使变量也在工作包含两个字符,但我又添加了两个字符 1995 ,它给了我95.





However this second code, is working even if the variable contains two characters, but I added 2 more to make it 1995, and it gave me 95.

// variable
int year = 1995;
// write the string without first two characters
Console.WriteLine(year.ToString().Remove(0, 2));





那么你可以做些什么来减少这个,就是在你继续之前检查字符是否足够,





So what might you do to minimize this, is to check if the characters are enough before you proceed as,

if(expYear.Length > 1) {
   // if contains more than 1 character, then
   lblDataForYear.Text = expYear.ToString() + "/" + 
                         (expYear + 1).ToString().Remove(0,2);
}


您好,



请试试这个:



Hi,

please try this:

string text = "the quick brown fox jumps over the lazy dog";

string subText = text.Substring(2, text.Length - 2);





这将给出:快速棕色狐狸跳过懒狗。



祝你好运,

Stephan



This will give: "e quick brown fox jumps over the lazy dog".

Best regards,
Stephan


这篇关于索引和计数必须引用字符串中的位置。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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