Python:
def snip_at_word_boundary(text: str, n: int) -> str:
"""
Return a version of `text` trimmed to <= n characters
without cutting a word in the middle.
"""
if len(text) <= n:
return text
# Cut at the limit first
snippet = text[:n]
# If the next character is a space, we're already at a boundary
if text[n:n+1] == " ":
return snippet.rstrip()
# Otherwise, roll back to the last space
last_space = snippet.rfind(" ")
if last_space == -1:
# No spaces at all before n — return the first word fully
return snippet.rstrip()
return snippet[:last_space].rstrip()