-4
A
回答
3
我知道的最快方法是:
var result = s.Length < n ? s : s.Substring(0, n);
0
最好的辦法是寫一對夫婦的擴展方法。
然後,你可以使用它像string result = sourceString.Left(10);
public static class StringExt
{
/// <summary>
/// Returns the first <paramref name="count"/> characters of a string, or the entire string if it
/// is less than <paramref name="count"/> characters long.
/// </summary>
/// <param name="self">The string. Cannot be null.</param>
/// <param name="count">The number of characters to return.</param>
/// <returns>The first <paramref name="count"/> characters of the string.</returns>
public static string Left(this string self, int count)
{
Contract.Requires(self != null);
Contract.Requires(count >= 0);
Contract.Ensures(Contract.Result<string>() != null);
// ReSharper disable PossibleNullReferenceException
Contract.Ensures(Contract.Result<string>().Length <= count);
// ReSharper restore PossibleNullReferenceException
if (self.Length <= count)
return self;
else
return self.Substring(0, count);
}
/// <summary>
/// Returns the last <paramref name="count"/> characters of a string, or the entire string if it
/// is less than <paramref name="count"/> characters long.
/// </summary>
/// <param name="self">The string. Cannot be null.</param>
/// <param name="count">The number of characters to return.</param>
/// <returns>The last <paramref name="count"/> characters of the string.</returns>
public static string Right(this string self, int count)
{
Contract.Requires(self != null);
Contract.Requires(count >= 0);
Contract.Ensures(Contract.Result<string>() != null);
// ReSharper disable PossibleNullReferenceException
Contract.Ensures(Contract.Result<string>().Length <= count);
// ReSharper restore PossibleNullReferenceException
if (self.Length <= count)
return self;
else
return self.Substring(self.Length - count, count);
}
}
0
點點慢於Superbest's solution:
string result = s.Substring(0, Math.Min(s.Length, n));
相關問題
- 1. 使N個字符的字符串
- 2. 使用sed獲取前N個字符和後N個字符
- 3. 如何使用VBScript去除字符串的前n個字符?
- 4. 將字符串N拆分爲N/X個字符串
- 5. 如何讀取字節流的前n個字符?並與字符串比較
- 6. 從字符串獲取n個字符
- 7. 分割字符串由N個字符
- 8. 拆分字符串每n個字符
- 9. PHP取前n個字符,並從原來的字符串
- 10. 返回unicode字符串的前N個字符
- 11. 返回字符串的前n個字符
- 12. Twitter bootstrap顯示字符串的前n個字符
- 13. 正則表達式匹配字符串的前n個字符
- 14. 如何使用java反轉n個字符串中的n個字符
- 15. 使字符串中的前N個字母變爲粗體?
- 16. 從字符串前移至n個字符到最後
- 17. 字符串中的第N個字
- 18. 帶n個字母的字符串
- 19. 找換行字符「\ n」的字符串
- 20. Python:Split字符串中的每n個字的分割字符串
- 21. 捕獲字符串,只有n個字
- 22. 第n個字符
- 23. 如何分割的python字符串中的每個第n-1 + n個字符
- 24. 如何使用PHP從字符串中刪除前n個數字字符?
- 25. 每N個字符/數字分割一個字符串/數字?
- 26. 截斷字符串中的最後n個字符使用.format()
- 27. 捕獲每行的前n個字符
- 28. 加下劃線的前n個字符
- 29. 小寫的前n個字符
- 30. uniq的跳過前N個字符/場
簡單,但效率不高:'VAR的結果=新的字符串(s.Take(N).ToArray ());' – 2015-04-06 07:34:32