[英]Common Lisp Concatenate and newline
我當前正在編寫一個LISP程序,該程序以如下形式對CR結果進行分析:(“ I” 0 10 0 20)<<(字X0 X1 Y0 Y1)
它必須使用單詞的位置來構建整個文本。 我的代碼有一個群集分析器,可以找出群集布局,例如具有左對齊或右對齊甚至雙對齊的段落。 群集數據結構看起來像這樣:(“群集名稱” xline y0 y1'(群集詞))
在遍歷字符串列表並將它們連接到結果字符串以從中創建格式化文本時,如何添加新行? 例:
"Hi,\n
\n
here is my entry\n
\n
Good bye"
我的代碼如下所示:
(defun print-formatted-text(txt)
(let
((size (array-total-size txt))
(sorted (sort (sort txt #'compare-mix) #'compare-generic2))
(result ""))
(loop for i from 0 to (1- size) do
(let ((el (aref sorted i)))
(if (word? el)
(setf result (concatenate 'string result (first el) " "))
(if (null (nth 7 el))
nil
(progn
(setf result (concatenate 'string result " "))
(dolist (curr (nth 7 el))
(setf result (concatenate 'string result (first curr) " "))))))))
result))
如果當前數據不是單詞,則為段落。 這意味着,我需要在添加段落之前和之后添加新行。
在這里正確使用串聯嗎?
感謝您的建議。
我不太了解您的程序,但是使用字符串流並使用format
, write-string
, write-line
, terpri
和相關功能要容易得多,例如
(let ((lines '("Hi," "Here is my entry" "Good bye")))
(with-output-to-string (stream)
(dolist (line lines)
(write-line line stream)
(terpri stream))))
=>
"Hi,
Here is my entry
Good bye
"
有關編碼風格的幾件事
(defun print-formatted-text(txt)
(let
((size (array-total-size txt))
(sorted (sort (sort txt #'compare-mix) #'compare-generic2))
(result ""))
(loop for i from 0 to (1- size) do
(let ((el (aref sorted i)))
(LOOP FOR e1 ACROSS
進行排序
(if (word? el)
(setf result (concatenate 'string result (first el) " "))
重復串接字符串確實很浪費。 正如Xach所說,STREAMS是更好的抽象。
(if (null (nth 7 el))
nil
(progn
使用:( (when (nth 7 e1)
(setf result (concatenate 'string result " "))
(dolist (curr (nth 7 el))
(setf result (concatenate 'string result (first curr) " "))))))))
result))
如果在字符或換行符上使用串聯,則需要用括號括起來,以便它是一個列表,例如'(#\\Newline)
。
其中#\\ Newline是換行符。
必須將所有字符(例如從字符串中提起的字符)(像這樣(elt "abc" 1)
做成一個列表,像這樣(list (elt "abc" 1)
。
例如代碼:
(concatenate 'string "Hi ther" '(#\\e) "." '(#\\Newline) "How " (list #\\a #\\r #\\e) " you!" ) => "Hi there. How are you!"
你可以試試這個
(format nil "~%")
例如
(setf result (concatenate 'string result (format nil "~%")))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.