c#编译子字符串错误

本文关键字:错误 字符串 编译 | 更新日期: 2023-09-27 18:13:33

为什么我得到:

Index and length must refer to a location within the string.
Parameter name: length

,当我编译这段代码:http://pastebin.com/CW4EcCM8

part of it:

    public string findFileEnding(string file)
    {
        int index1 = file.IndexOf('.');
        file = file.Substring(index1, file.Length);
        return file;
    }

谢谢,)

c#编译子字符串错误

我认为Path.GetExtension可能是OP可能想要的东西。

请注意,它返回.扩展,如.exe

http://msdn.microsoft.com/en-us/library/system.io.path.getextension.aspx

Substring的第二个参数(如果存在)是子字符串的期望长度。所以你要求一个与file长度相同的字符串,但从一个可能不同于0的位置开始。这将使子字符串的末尾超过file的末尾。

假设您想让所有file从位置index1开始,您可以完全省略第二个参数:

file = file.Substring(index1); 

为了使其健壮,您将需要添加更多检查:

  1. file可能是null
  2. IndexOf的返回值可以是-1。如果file不包含点,则会发生这种情况。

这不是编译错误,这是运行时错误。

注意String.Substring(int, int)的文档:

从此实例检索子字符串。子字符串从指定的字符位置[startIndex]开始,具有指定的长度[length]。

因此子字符串将具有指定的长度。因此,必须有足够的从startIndex开始的字符来返回指定长度的子字符串。因此,String.Substring要在string的实例s上成功,必须满足以下不等式:
startIndex >= 0
length >= 0
length > 0 implies startIndex + length <= s.Length

注意,如果您只想要从index到字符串末尾的子字符串,您可以输入

s.Substring(index);

这里,唯一的约束是

startIndex>= 0
startIndex < s.Length

您可能希望这样做:

public string FindFileEnding(string file)
{
    if (string.IsNullOrEmpty(file))
    {
        // Either throw exception or handle the file here
        throw new ArgumentNullException();
    }
    try
    {
        return file.Substring(file.LastIndexOf('.'));
    }
    catch (Exception ex)
    {
        // Handle the exception here if you want, or throw it to the calling method
        throw ex;
    }
}