Add TruncateString to shorten a string without splitting a character #5
Reference in New Issue
Block a user
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Cutting a string with a plain byte slice such as
s[:80]will split amulti-byte character in half and produce invalid text, which shows up as a
replacement character in logs, database columns and terminal output. A short
function that counts characters instead of bytes makes the safe version the
easy one.
Definition of done:
TruncateString(s string, max int) stringreturns at mostmax characters from the start of s, never cutting a multi-byte character, and
returns an empty string when max is zero or less. It has a doc comment and
table-driven tests covering a string shorter than the limit, a string exactly
at the limit, a string longer than the limit, a string of multi-byte
characters, a max of zero, and a negative max.
Model: opus-5