-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