Skip to content

Instantly share code, notes, and snippets.

@OnSive
Created December 8, 2020 09:21
Show Gist options
  • Select an option

  • Save OnSive/6285f3173e4f4f36bf6aa255a29a3255 to your computer and use it in GitHub Desktop.

Select an option

Save OnSive/6285f3173e4f4f36bf6aa255a29a3255 to your computer and use it in GitHub Desktop.
[Fix length] Returns a string with a fixed length #Text
/// <summary>
/// Returns a string with a fixed length
/// </summary>
/// <param name="sText">The text which should be checked</param>
/// <param name="iLength">The wished length of the text</param>
/// <param name="bKeepEnd">If instead of cutting the end, the beginning should be cut</param>
/// <returns>
/// Returns the text with the passed length. Either its cut at the end or beginning, or filled up with
/// spaces.
/// </returns>
public static string FixLength(this string sText, int iLength, bool bKeepEnd = false)
{
// Check if the length is longer
if (sText.Length > iLength)
{
if (bKeepEnd)
{
// Shortens the string and inserts two points
return $"..{sText.Substring((sText.Length - iLength) + 2)}";
}
else
{
// Shortens the string and inserts two points
return $"{sText.Substring(0, iLength - 2)}..";
}
}
else
{
// Fills up the rest with spaces
return sText.PadRight(iLength, ' ');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment