[英]C# substring throws an exception
這是我的代碼:
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
方法的版本,該版本允許您指定要提取的字符數。
但是,您要提供length
參數作為字符串本身的整個長度-因此是ArgumentOutOfRangeException
。
如果使用此版本的String.Substring
,則可以提供一個參數( startIndex
),然后自動從提供的索引處獲取其余的字符串。
因此,您可以從此更改代碼:
return pth.Substring(pth.IndexOf('-')+1, pth.Length).Trim();
對此:
return pth.Substring(pth.IndexOf('-')+1).Trim();
Substring(int index, int length)
, length
應該是子字符串的長度,而不是整個字符串的長度。
你要:
int index = pth.IndexOf('-');
return pth.Substring(index + 1, pth.Length - index - 1);
問題是您正在嘗試檢索比您指定的長度短的子字符串。 另外,如果字符'-'
位於字符串的末尾,則將獲得異常,因為index+1
將在字符串之外。 這將有助於:
private string title(string pth) //I'm passing a path
{
pth = System.IO.Path.GetFileNameWithoutExtension(pth); // I need an exact filename with no extension
string retStr = string.Empty;
if(pth.IndexOf('-')<pth.Length-1)
{
retStr = pth.Substring(pth.IndexOf('-')+1).Trim(); // trying to return everything after '-'
}
return retStr;
}
我建議在這種情況下使用正則表達式。 就像是:
private static string title(string pth)
{
pth = System.IO.Path.GetFileNameWithoutExtension(pth); // I need an exact filename with no extension
Match m = Regex.Match(pth, @".*\-(?<suffix>.*)$");
Group suffix = m.Groups["suffix"];
return suffix.Success ? suffix.Value : pth;
}
干凈得多。
我不知道您的例外是什么,但我假設這-
您的字符串中不存在。
如果在此處查看String.IndexOf
的文檔,您將看到:
如果找到該字符串,則從零開始的索引位置;如果未找到,則返回-1
當您使用-1
開始索引創建subString
時,它將引發異常。
我會先檢查-
的存在,然后如果找到,則執行子字符串:
if(pth.IndexOf('-') != -1)
{
//Substring code
}
首先,您應該告訴我們您的例外情況。 那會有所幫助
pth.Substring(pth.IndexOf('-')+1, pth.Length)
看起來會拋出異常,因為它將嘗試使用超出長度的子字符串。
嘗試
pth.Substring(pth.IndexOf('-')+1)
代替
String.Substring方法的第二個參數是子字符串的長度。 在這種情況下,子字符串的長度應始終小於第pth字符串的長度。 您可能打算這樣做:
private string title(string pth) //I'm passing a path
{
pth = System.IO.Path.GetFileNameWithoutExtension(pth);
return pth.Substring(pth.IndexOf('-')+1, pth.Length - pth.IndexOf('-') - 1).Trim();
}
您需要像這樣更改代碼:
private string title(string pth) //I'm passing a path
{
pth = System.IO.Path.GetFileNameWithoutExtension(pth);
var indexOfDash = pth.IndexOf('-') + 1; // Add this line
return pth.Substring(indexOfDash, pth.Length - indexOfDash).Trim();
}
您可以按以下方式使用LINQ:
string someString = "abcde";
string subStr = string.Join("", someString.Take(240));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.