2011-11-04 36 views
0

为什么我越来越:C#编译器错误与子串

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

当我编译此代码: http://pastebin.com/CW4EcCM8

它的某些部分:

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

感谢;)

+0

有没有支票,索引1是> -1(这还出现了。在字符串中)。如果你做一个子字符串W /索引:-1它也会引发错误... – Rikon

+1

不是你的问题的答案,但更可靠的方式来找到文件扩展名是使用路径类:http:// msdn。 microsoft.com/en-us/library/system.io.path.aspx –

+0

@Rikon相同的错误,但有不同的信息... –

回答

2

Substring的第二个参数(如果存在)是所需的长度o f子串。因此,您要求的字符串的长度与file的长度相同,但是从可能不同于0的位置开始。这会使您的子字符串的末尾超过file的末尾。

假设你想获得的所有的file开始index1位置,你可以离开了第二个参数干脆:

file = file.Substring(index1); 

为了使这个强大的,你会希望把一些更多的检查:

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

可能想提及OP应该检查返回-1的'IndexOf'。 – CodeNaked

0

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

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

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

所以将有指定的长度。因此,从startIndex开始必须有足够的字符才能返回指定长度的子字符串。因此,下面的不等式必须满足String.Substringsstring的实例成功:

startIndex >= 0 
length >= 0 
length > 0 implies startIndex + length <= s.Length 

请注意,如果你只是想从index到字符串末尾的子串,你可以说

s.Substring(index); 

在这里,唯一的限制是

startIndex>= 0 
startIndex < s.Length 
0

你会想要做类似日是:

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; 
    } 
} 
+0

我假设你的意思是'string.IsNullOrEmpty(file)'为你的第一个if语句,因为除非你定义了自定义的扩展方法,否则你所拥有的是无效的。你还应该检查'LastIndexOf'的返回值。重新思考这个例外是没有道理的。 – CodeNaked

+0

@CodeNaked感谢代码检查,很难在浏览器中完成。那里有任何验证C#的网站吗?它并不意味着完整的答案,只是一个起点。如果最后一个索引无效,那么您必须在处理之前或之后处理它。我原本用'int index = file.LastIndexOf('。')'把它删除了,因为没有任何说明他们想如何处理错误或错误的值 – John

+1

我不知道有任何网站可以这样做,但那里是一些[轻量级工具](http://stackoverflow.com/questions/2775055/looking-for-replacement-for-snippet-compiler)。 – CodeNaked