在 Racket 中截断字符串

Truncate strings in Racket

有没有一种简单的方法可以在 Racket 中将字符串截断到一定宽度?

示例:

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

我还想替换截断字符串的最后几个字符:

(truncate "foobar" 4 #:when-truncated "...")
-> "f..."
(truncate "foobar" 10 #:when-truncated "...")
-> "foobar"

您可以使用带有 #:max-width#:limit-marker 关键字的 ~a 函数来截断字符串。

例如:

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

计算为 "f..."

另一方面:

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

计算为 "foo"

You can find the documentation for this function here.