说我有字符串s
。如果s
短于s
个字符,我想返回n
,否则返回s.Substring(0, n)
。
最简单的方法是什么?
答案 0 :(得分:3)
我所知道的最快捷方式是:
var result = s.Length < n ? s : s.Substring(0, n);
答案 1 :(得分:1)
比Superbest's solution慢一点:
string result = s.Substring(0, Math.Min(s.Length, n));
答案 2 :(得分: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);
}
}
答案 3 :(得分:0)
如果字符串较短或等于所需长度,则只需返回字符串即可。不要仅仅为了返回整个字符串而调用Substring
。
var result = s.Length <= n ? s : s.Substring(0, n);