截断Racket中的字符串

Ben*_*man 6 string format racket

是否有一种简单的方法可以在Racket中将字符串截断为特定宽度?

例子:

(truncate "foobar" 3)
-> "foo"
(truncate "foobar" 6)
-> "foobar"
Run Code Online (Sandbox Code Playgroud)

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

(truncate "foobar" 4 #:when-truncated "...")
-> "f..."
(truncate "foobar" 10 #:when-truncated "...")
-> "foobar"
Run Code Online (Sandbox Code Playgroud)

Lei*_*sen 6

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

例如:

(~a "foobar" #:max-width 4 #:limit-marker "...")
Run Code Online (Sandbox Code Playgroud)

评估为"f...".

另一方面:

(~a "foo" #:max-width 4 #:limit-marker "...")
Run Code Online (Sandbox Code Playgroud)

评估为"foo".

您可以在此处找到此功能的文档.