【发布时间】:2015-04-06 07:27:28
【问题描述】:
假设我有字符串s。如果s 比n 字符短,我想返回s,否则返回s.Substring(0, n)。
最简单的方法是什么?
【问题讨论】:
假设我有字符串s。如果s 比n 字符短,我想返回s,否则返回s.Substring(0, n)。
最简单的方法是什么?
【问题讨论】:
我知道的最快的方法是:
var result = s.Length < n ? s : s.Substring(0, n);
【讨论】:
var result = new string(s.Take(n).ToArray());
比Superbest's solution慢一点点:
string result = s.Substring(0, Math.Min(s.Length, n));
【讨论】:
最好的方法是编写几个扩展方法。
那么你就可以像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);
}
}
【讨论】:
如果字符串短或等于所需长度,则返回字符串。不要仅仅为了返回整个字符串而调用Substring。
var result = s.Length <= n ? s : s.Substring(0, n);
【讨论】: