c# - C#子字符串引发异常

标签 c# .net string

这是我的代码:

private string title(string pth) //I'm passing a path
{
    pth = System.IO.Path.GetFileNameWithoutExtension(pth); // I need an exact filename with no extension
    return pth.Substring(pth.IndexOf('-')+1, pth.Length).Trim(); // trying to return everything after '-'
}


它引发异常。我不知道为什么。这是从文件名中获取标题的极其简单的方法,但是它不起作用。

我已经尝试过pth.Length-1,但是它也不起作用。

最佳答案

您正在使用String.Substring method的版本,该版本允许您指定要提取的字符数。

但是,您要提供length参数作为字符串本身的整个长度,因此也就是ArgumentOutOfRangeException

如果使用this version of String.Substring,则可以提供一个参数(startIndex),然后自动从提供的索引处获取其余字符串。

因此,您可以从此更改代码:

return pth.Substring(pth.IndexOf('-')+1, pth.Length).Trim();


对此:

return pth.Substring(pth.IndexOf('-')+1).Trim();

关于c# - C#子字符串引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13570360/

相关文章:

.net - 加快 LINQ 查询速度的技巧?

string - 在包含花括号的字符串上使用 -f 运算符

c++ - 字符串不会打印

c# - 如何随机分配按钮内容和颜色?

c# - 如何检查用户控件是否在 C# 中的其他控件前面?

c# - 用户确认的异步命令执行

python - 如何检查字符串是否与 Python 中的设置模式匹配?

c# - Asp.net MVC ViewEngineResult + 嵌入式 View

c# - 泛型、枚举和自定义属性——这可能吗?

c# - WF8 & C# & SQLite & 自动增量 & 失败