|
|
|
@ -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 字符串的方式,下面来一一说明。
|
|
|
|
|