From 464d4add74b745346f0ccdf4d1bed29a6e59e32d Mon Sep 17 00:00:00 2001 From: sunface Date: Tue, 12 Apr 2022 10:50:21 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?UTF-8?q?=E8=BD=AC=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/basic/compound-type/string-slice.md | 47 ++++++++++++++++++++++++- 内容变更记录.md | 4 +++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/basic/compound-type/string-slice.md b/src/basic/compound-type/string-slice.md index cbab31be..f84cd10c 100644 --- a/src/basic/compound-type/string-slice.md +++ b/src/basic/compound-type/string-slice.md @@ -449,7 +449,7 @@ fn main() { 代码运行结果: ```console -string_remove 占 18 个字 +string_remove 占 18 个字节 string_remove = "试remove方法" ``` @@ -579,6 +579,51 @@ fn main() { hello rust! ``` +## 字符串转义 + +我们可以通过转义的方式 `\` 输出 ASCII 和 Unicode 字符。 + +```rust +fn main() { + // 通过 \ + 字符的十六进制表示,转义输出一个字符 + let byte_escape = "I'm writing \x52\x75\x73\x74!"; + println!("What are you doing\x3F (\\x3F means ?) {}", byte_escape); + + // \u 可以输出一个 unicode 字符 + let unicode_codepoint = "\u{211D}"; + let character_name = "\"DOUBLE-STRUCK CAPITAL R\""; + + println!( + "Unicode character {} (U+211D) is called {}", + unicode_codepoint, character_name + ); + + // 换行了也会保持之前的字符串格式 + let long_string = "String literals + can span multiple lines. + The linebreak and indentation here ->\ + <- can be escaped too!"; + println!("{}", long_string); +} +``` + +当然,在某些情况下,可能你会希望保持字符串的原样,不要转义: +```rust +fn main() { + println!("{}", "hello \\x52\\x75\\x73\\x74"); + let raw_str = r"Escapes don't work here: \x3F \u{211D}"; + println!("{}", raw_str); + + // 如果字符串包含双引号,可以在开头和结尾加 # + let quotes = r#"And then I said: "There is no escape!""#; + println!("{}", quotes); + + // 如果还是有歧义,可以继续增加,没有限制 + let longer_delimiter = r###"A string with "# in it. And even "##!"###; + println!("{}", longer_delimiter); +} +``` + ## 操作 UTF-8 字符串 前文提到了几种使用 UTF-8 字符串的方式,下面来一一说明。 diff --git a/内容变更记录.md b/内容变更记录.md index 70c90dea..d02646eb 100644 --- a/内容变更记录.md +++ b/内容变更记录.md @@ -1,6 +1,10 @@ # ChangeLog 记录一些值得注意的变更。 +## 2022-04-12 + +- [优化字符串章节,增加字符串转义](https://course.rs/basic/compound-type/string-slice.html#字符串转义) + ## 2022-04-11 - 增加 [OnceCell](https://course.rs/advance/global-variable.html#标准库中的-oncecell), 感谢 [Rustln](https://github.com/rustln) 提交的 PR