[英]How can I do take a substring and length of a string in C# if that string might be a null?
[英]C# take a substring of a string
我僅從文件中提取一行,除非該文件沒有特定的模式..我想從該行中提取最后3個字符...我的代碼是:
while (!line.Contains(pattern))
{
String num = line.Substring((line.Length - 3), (line.Length - 2));
System.Console.WriteLine(num);
}
但我得到一個錯誤..
索引和長度必須引用字符串中的位置。 參數名稱:長度
為什么我明白了? 我在該行的末尾開始3個字符的新字符串,並且在此之前停止2個字符。.:\\
子字符串采用偏移量,然后返回多個字符:
http://msdn.microsoft.com/zh-cn/library/aa904308%28v=VS.71%29.aspx
所以:
String num = line.Substring((line.Length - 3), 3);
當然,這是假設line.Length>3。您可以使用以下命令進行檢查:
String num = (line.Length < 3) ? line : line.Substring((line.Length - 3), 3);
Substring
第二個參數是從第一個參數開始必須帶多少個字符。 它看起來應該像這樣: String num = line.Substring(line.Length - 3, 3);
問題是您嘗試獲取的字符數要多於數組擁有的字符數。
擴展最適合解決此類問題;)我的名字有些骯臟,但是每個人都知道它會做什么-這是異常安全的子字符串:
public static string SubstringNoLongerThenSource(this string source, int startIndex, int maxLength)
{
return source.Substring(startIndex, Math.Min(source.Length - startIndex, maxLength));
}
因此,在您的確切問題中,它應該是這樣的:
String num = line.SubstringNoLongerThenSource((line.Length - 3), 3);
System.Console.WriteLine(num);
因此,如果您提供給函數的字符串具有足夠的字母,則num將最多包含3個字母:)
這很危險。 如果行的長度小於3怎么辦? 您可能應該檢查一下,否則會出現異常。
此外,你應該使用的子方法描述在這里 :
String num = line.Substring((line.Length - 3), 3);
String num = line.Substring(line.Length - 3)
發生這種情況是因為Substring()的最后一個參數應該是要提取的字符串的長度。
您的情況應該是3
,而不是line.Length - 2
第一個參數還應該是:
line.Length - 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.