我用下面的:尋找一個簡單的方法來截斷在C#中的字符串
t.Description.Substring(0, 20)
但有,如果有字符串中少於20個字符的問題。有一種簡單的方法(單行內聯函數),當字符串少於20個字符時,我可以使用它來截斷最大值而不會出現錯誤?
我用下面的:尋找一個簡單的方法來截斷在C#中的字符串
t.Description.Substring(0, 20)
但有,如果有字符串中少於20個字符的問題。有一種簡單的方法(單行內聯函數),當字符串少於20個字符時,我可以使用它來截斷最大值而不會出現錯誤?
如何:
t.Description.Substring(0, Math.Min(0, t.Description.Length));
有點難看,但會起作用。或者,寫一個擴展方法:
public static string SafeSubstring(this string text, int maxLength)
{
// TODO: Argument validation
// If we're asked for more than we've got, we can just return the
// original reference
return text.Length > maxLength ? text.Substring(0, maxLength) : text;
}
什麼
t.Description.Take(20);
編輯
由於上面的代碼將在字符數組infacr結果,正確的代碼會是這樣:
string.Join("", t.Description.Take(20));
這將返回一個IEnumerable的''
喬恩 - 正如你所看到的,我意識到自己,我不得不說,第一行代碼看起來比我編輯之前更好;)。感謝提醒我,有一個字符串構造函數將char數組作爲參數。 –
使用
string myShortenedText = ((t == null || t.Description == null) ? null : (t.Description.Length > maxL ? t.Description.Substring(0, maxL) : t));
另:
var result = new string(t.Description.Take(20).ToArray());
我很喜歡這個,因爲我已經對字符串使用了一些擴展方法。 –