Kalkwst / MicroLib

MIT License
3 stars 0 forks source link

:sparkles: Text: Add WordUtils.Abbreviate Function #7

Closed Kalkwst closed 1 year ago

Kalkwst commented 1 year ago

This method abbreviates a given string by truncating it to a given length and appending a given string to the end. It takes in four parameters: the string to be abbreviated (str), the lower limit of how many characters the string should be shortened to (lower), the upper limit of how many characters the string should be shortened to (-1 meaning no upper limit) (upper), and the string to be appended to the end of the abbreviated string (appendToEnd).

If the upper limit is less than -1 or the lower limit is greater than the upper limit (except when the upper limit is -1), an exception is thrown.

If the input string is null or empty, it is returned as is. If the lower limit is greater than the length of the input string, the lower limit is set to the length of the input string. If the upper limit is -1 or greater than the length of the input string, the upper limit is set to the length of the input string.

The method then finds the index of the first space character in the string after the lower limit and either truncates the string to the upper limit or to the index of the space character (whichever is smaller) and appends the appendToEnd string to the end before returning the result.

Suppose no space character is found in the string after the lower limit. In that case, the string is truncated to the upper limit and the appendToEnd string is only appended if the string was actually truncated (the upper limit is not equal to the length of the input string).