I have a string that must be truncated at 200 characters if it is too long.
Checking the cheatsheet, (subs "Lorem Ipsum" 0 200)
would seem to be an obvious choice, but it throws an exception if the second operator is greater than the length of the string.
Is there a simple, built-in function for truncating a string in Clojure? What's the simplest way to do this if I have to define my own?
Truncate the string (first argument) if it is longer than the given maximum string length (second argument) and return the truncated string with a ... ending. The inserted three dots at the end should also add to the string length.
Truncation in IT refers to “cutting” something, or removing parts of it to make it shorter. In general, truncation takes a certain object such as a number or text string and reduces it in some way, which makes it less resources to store.
The other way to truncate a string is to use a rsplit() python function. rsplit() function takes the string, a delimiter value to split the string into parts, and it returns a list of words contained in the string split by the provided delimiter.
Use syntax string[x:y] to slice a string starting from index x up to but not including the character at index y. If you want only to cut the string to length in python use only string[: length].
You can check the length beforehand or use min
to determine the actual number of characters that will remain:
(defn trunc
[s n]
(subs s 0 (min (count s) n)))
You can treat them as sequences and get safety (and elegance?) but the cost is performance:
(defn truncate
[s n]
(apply str (take n s)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With