Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate strings in Racket

Is there an easy way to truncate strings to a certain width in Racket?

Examples:

(truncate "foobar" 3)
-> "foo"
(truncate "foobar" 6)
-> "foobar"

I'd also like to replace the last few characters of a truncated string:

(truncate "foobar" 4 #:when-truncated "...")
-> "f..."
(truncate "foobar" 10 #:when-truncated "...")
-> "foobar"
like image 613
Ben Greenman Avatar asked Aug 17 '15 22:08

Ben Greenman


1 Answers

You can use the ~a function with the #:max-width and #:limit-marker keywords to truncate strings.

For example:

(~a "foobar" #:max-width 4 #:limit-marker "...")

evaluates to "f...".

On the other hand:

(~a "foo" #:max-width 4 #:limit-marker "...")

evaluates to "foo".

You can find the documentation for this function here.

like image 161
Leif Andersen Avatar answered Nov 07 '22 13:11

Leif Andersen