Adjust Text to Specific Length

by Feb 21, 2013

If you must make sure that a text has a fixed length and is neither shorter nor longer, here is the code to pad and cut the text to the desired length:

$text1 = 'some short text'
$text2 = 'some very very very very long text'
$desiredLength = 20
$text1 = $text1.PadRight($desiredLength).SubString(0, $DesiredLength)
$text2 = $text2.PadRight($desiredLength).SubString(0, $DesiredLength)
$text1 + "<- ends here"
$text2 + "<- ends here"

By combining PadRight() and SubString(), the text is adjusted to the desired length, no matter how long or short the text was before:

some short text     <- ends here
some very very very <- ends here

Twitter This Tip! ReTweet this Tip!