Reputation: 26612
Say I have string s
. I want to return s
if s
is shorter than n
characters, and otherwise return s.Substring(0, n)
.
What's the easiest way of doing this?
Upvotes: 5
Views: 4915
Reputation: 2492
If the string is shorter or equal to the desired length, just return the string. Do not call Substring
just to return the entire string.
var result = s.Length <= n ? s : s.Substring(0, n);
Upvotes: 0
Reputation: 574
Tiny bit slower than Superbest's solution:
string result = s.Substring(0, Math.Min(s.Length, n));
Upvotes: 4
Reputation: 109742
Best approach is to write a couple of extension methods.
Then you can just use it like 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);
}
}
Upvotes: 0
Reputation: 26612
The quickest way I know is:
var result = s.Length < n ? s : s.Substring(0, n);
Upvotes: 11