如何在 elisp 中将字符串居中?
我想将给定的输入字符串居中对齐到给定的大小,以便生成一个在输入字符串的两侧(左侧和右侧)填充空格的字符串。
我必须执行此操作的代码:
(defun center-string (string size)
(let* ((padding (/ (- size (length string)) 2))
(lpad (+ (length string) padding))
(lformat (format "%%%ds" lpad))
(rformat (format "%%%ds" (- size))))
(format rformat (format lformat string))))
以及一些测试用例:
(center-string "KJF" 10)
=> " KJF "
(center-string "KF" 10)
=> " KF "
(center-string "0123456789" 10)
=> "0123456789"
(center-string "0123456789" 5)
=> "0123456789" ; Notice justifcation is ignored as input string too large.
是否有现有的 elisp 函数可以执行此操作或更好的方法?
I would like to center justify a given input string to a given size so that what is produced is a string with padded spaces either side (left and right) of the input string.
The code I have to do this:
(defun center-string (string size)
(let* ((padding (/ (- size (length string)) 2))
(lpad (+ (length string) padding))
(lformat (format "%%%ds" lpad))
(rformat (format "%%%ds" (- size))))
(format rformat (format lformat string))))
And some test cases:
(center-string "KJF" 10)
=> " KJF "
(center-string "KF" 10)
=> " KF "
(center-string "0123456789" 10)
=> "0123456789"
(center-string "0123456789" 5)
=> "0123456789" ; Notice justifcation is ignored as input string too large.
Is there an existing elisp function to do this or a better method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一个
center-line
,它在缓冲区中工作(并使用缓冲区的fill-column
值作为行长度),所以如果您的目标是产生一个很好的效果格式化文件,你可以这样做There's a
center-line
, which works in a buffer (and uses the buffer's value offill-column
as the line length), so if your goal is to produce a nicely formatted file, you could do something like不,没有现有的 emacs lisp 例程可以完成您想要的操作。 (通过 emacs lisp info 和 emacs info 的标准搜索支持这一点)。
No, there is not an existing emacs lisp routine that does what you want. (the standard search through emacs lisp info and emacs info supports this).