索引和长度必须指向字符串中的位置。 [英] Index and length must refer to a location within the string.

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

问题描述

我正在提取一个像这个字符串的字符串xValue = final [6] [1] .Substring(0,6);



当值为0.9789时没有显示任何错误,但如果值是某个整数,如14,它给索引和长度必须引用字符串异常中的位置。但我怎么能处理这两种情况?



string [] [] final = ListofSpectraImagesForAllLocation.ElementAt(index).Value;

I am extracting a substring like this string xValue = final[6][1].Substring(0, 6);

when the value is 0.9789 it is not showing any error but if the value is some integer like 14 it is giving Index and length must refer to a location within the string exception.But how can i handle both the situations?

string[][] final = ListofSpectraImagesForAllLocation.ElementAt(index).Value;

推荐答案

你可以调用.ToString(#。000000)确保它始终至少具有您需要的小数位数。



但是,我仍然建议解析小数可能不是一个好主意,它将有助于知道你实际上想要做什么。似乎应该有更好的方法。
You can call .ToString("#.000000") to make sure it always has at least the number of decimal places you need.

However, I still suggest that parsing decimals is probably not a good idea and it would help to know what you are actually trying to do. Seems like there should be a better way.


你的var是int将它改为字符串

your var is int change it to string
xValue = final[6][1].ToString().Substring(0, 6);



控制错误


control error

int final;
          int  len = final.ToString().Length;
            if (len < 6)
            {
                xValue = final[6][1].ToString().Substring(0, len);
            }
            else
            {
                xValue = final[6][1].ToString().Substring(0, 6);
            }


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

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