# 4.6 字符串转换

本节介绍了字符、字符串和整数之间进行转换的函数。函数 format 和 函数 prin1-to-string 可以将 Lisp 对象转换为字符串。函数 read-from-string 可以将 字符串转换为对应的 Lisp 对象。函数 string-to-multibyte 和 函数 string-to-unibyte 可以改变字符串的文本表示。

\--

函数: number-to-string number

该函数返回数字对应的十进制的字符表示。如果参数为负值，那么返回值会以一个减号开头。

```
(number-to-string 256)
     ⇒ "256"
(number-to-string -23)
     ⇒ "-23"
(number-to-string -23.5)
     ⇒ "-23.5"
```

int-to-string  是该函数的一个别名。

参见 字符串格式化章节的 format 函数。

函数: string-to-number string & optional base

该函数返回字符串对应的数字。若参数 base 要么为 nil，要么为 2-16 之间的一个整数，该参数会作为转换的基数。若参数 base 为 nil，则意味着使用十进制，浮点数转换仅在十进制的时候才会生效；我们没有实现基于其他进制的浮点数转换，因为他们很复杂，而且似乎也没啥用。若一个字符串对应的整数大小超出了 Lisp 整数的范围，那么该函数会将其自动转换为浮点数，并作为结果返回。

字符串解析会跳过字符串起始位置空格、制表符，然后尽可能贪婪的读取可以转换为数字的字符。（在某些系统中，还会忽略其他的空白符号。）如果参数 string 不能被解释为数字，那么该函数会返回 0.

```
(string-to-number "256")
     ⇒ 256
(string-to-number "25 is a perfect square.")
     ⇒ 25
(string-to-number "X256")
     ⇒ 0
(string-to-number "-4.5")
     ⇒ -4.5
(string-to-number "1e5")
     ⇒ 100000.0
```

string-to-int 是该函数的一个别名。

函数: char-to-string character

该函数返回字符对应的字符串。这个函数即将被废弃，因为函数 string 更加通用。查阅 创建字符串章节。

函数: string-to-char string

这个函数返回 string 中出现的第一个字符。该函数和 (aref string 0) 非常相似，不同点在于若 string 为空，该函数会返回 0. (若 string 中第一个字符为 null 字符，ASCII 中的 0 ，则该函数也会返回 0.) 这个函数在将来可能会被废弃，以为它似乎不是很实用。

这里还有一些其他函数用于做字符串转换:

concat

该函数将向量或列表转换为字符串。详情查阅 创建字符串。

vconcat

该函数将字符串转换为向量。详情查阅 向量函数。

append

该函数将字符串转换为列表。详情查阅 构建列表。

byte-to-string

该函数将字符数据中的字节转换为单字节字符串。详情查阅 表示转换。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://emacs-lisp.ivory.cafe/zi-fu-chuan-he-zi-fu/zi-fu-chuan-zhuan-huan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
