Truncate strings in Racket
Asked Answered
B

1

6

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"
Bureaucrat answered 17/8, 2015 at 22:37 Comment(0)
Q
6

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.

Quadrisect answered 17/8, 2015 at 22:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.