我有一个字符和整数的列表,我试图将它们转换成一个字符串。
> (define l (cons #\a (cons #\b (cons 3 null))))
我想将这个列表转换为字符串"ab3"
。
使用list->string
不起作用:
> (list->string l)
list->string: contract violation
expected: (listof char?)
given: (list #\a #\b 3)
当我尝试将其与integer->char
相结合时,它会给出以下数值:
> (define l (cons #\a (cons #\b (cons (integer->char 3) null))))
> (list->string l)
"ab\u0003"
使用number->string
也不起作用:
> (define l (cons #\a (cons #\b (cons (number->string 3) null))))
> (list->string l)
list->string: contract violation
expected: (listof char?)
given: '(#\a #\b "3")
context...:
C:\Program Files\Racket\collects\racket\private\misc.rkt:87:7
list->string
需要一个字符列表,它不接受字符串。
另一次尝试,首先将字符串转换为列表:
> (define l (cons #\a (cons #\b (cons (string->list (number->string 123)) null))))
> (list->string l)
list->string: contract violation
expected: (listof char?)
given: '(#\a #\b (#\3))
context...:
C:\Program Files\Racket\collects\racket\private\misc.rkt:87:7
它也不接受子列表。如何将其转换为字符串"ab3"
发布于 2016-06-28 21:12:23
您希望处理字符和整数的列表,并将它们连接在一个字符串中。试试这个:
(define (process lst)
(apply string-append ; append all the strings
(map (lambda (e) ; create a list of strings
(if (char? e) ; if it's a char
(string e) ; convert it to string
(number->string e))) ; same if it's a number
lst)))
例如:
(process (list #\a #\b 123 #\c))
=> "ab123c"
发布于 2016-06-30 06:48:48
字符是具有值的类型。这个值是在unicode中定义的,因此65
是大写的A
,66
是大写的B
。所有字符都有整数值,char->integer
从字符转换为数字unicode值,integer->char
从unicode值转换为字符。
数字字符从48
(#x30
)开始,它是零到57
(#x39
),这是一个9。因此,(list->string (list #\a #\b (integer->number #x33))) ; ==> "ab3"
可以使用number->string
将数字值转换为字符串。例如:(number->string 123) => "123"
。这将显示在基数10中,但如果您希望它以十六进制显示,则可以使用(number->string 123 16) ;==> "7b"
。请注意,list->string
只接受一个字符列表,其中不能包含其他元素,比如数字。
您可以将多个字符串与string-append
连接起来。
(string-append (list->string '(#\a #\b))
(number->string #x7b)
"c")
; ==> "ab123c"
发布于 2022-11-19 06:43:06
Racket有一个名为~a
的方便的函数,它像使用display
一样将其参数转换为字符串,并将它们连接在一起(加上一组可选的关键字参数以控制格式设置,但这里不需要它们)。将它与apply
结合起来,将列表中的元素作为参数处理。
> (apply ~a '(#\a #\b 3))
"ab3"
(如果您使用的是#lang racket/base
,则必须使用(require racket/format)
)。
https://stackoverflow.com/questions/38089276
复制相似问题