在子字符串 C# 中获取超出范围的异常 [英] Getting out of range exception in Substring c#

查看:61
本文介绍了在子字符串 C# 中获取超出范围的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从//"的最后一个索引到文件长度打印文件名.
文件长度是 83 最后一个索引是 47 那么我在这里做错了什么

i am trying to print the Filename from last index of '//' till the file length.
file length is coming as 83 last index is coming as 47 then what wrong i am doing here

int idx = file.LastIndexOf('\\');
int fl=   file.Length;
string filename = file.Substring(idx, fl);

推荐答案

子字符串 不是from"、to"而是from"、length".

Substring is not "from", "to" but "from", "length".

从索引 47 和 83 个字符开始,超出了当前字符串的范围.

Starting at index 47 and 83 characters long is way out of the range of your current string.

如果您仍然想要字符串的其余部分,请使用

If you want the rest of the string anyway, use

string filename = file.Substring(idx);

也就是说,C# 有很好的 API 可以做到这一点.使用路径尽可能上课,不要手动执行此操作.

That said, C# has nice APIs for doing this. Use the Path class whenever possible and don't do this manually.

这篇关于在子字符串 C# 中获取超出范围的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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