Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to truncate a string in Clojure

Tags:

clojure

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?

like image 424
Brad Koch Avatar asked Dec 23 '13 16:12

Brad Koch


People also ask

How do you truncate a string?

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.

What does it mean to truncate a string?

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.

How do you truncate a string at a specific character in python?

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.

How do you shorten a string in python?

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].


2 Answers

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)))
like image 90
xsc Avatar answered Sep 19 '22 03:09

xsc


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)))
like image 36
ponzao Avatar answered Sep 19 '22 03:09

ponzao