Reputation: 20297
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?
Upvotes: 20
Views: 5026
Reputation: 20934
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)))
Upvotes: 8
Reputation: 6073
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)))
Upvotes: 29