rust(54)-字符串
Rust有兩種類型的字符串:String 和&str。
String 存儲(chǔ)為字節(jié)向量(Vec),但保證始終是有效的UTF-8序列。字符串是堆分配的,可增長(zhǎng)的,不以空null 結(jié)束。
&str是一個(gè)切片(&[u8]),它總是指向一個(gè)有效的UTF-8序列,并且可以用來(lái)查看String,就像&[T]是Vec的一個(gè)視圖一樣。
有多種方法可以編寫(xiě)包含特殊字符的字符串字面值。所有的結(jié)果都是一個(gè)相似的&str,所以最好使用最方便書(shū)寫(xiě)的表單。類似地,也有多種方法來(lái)編寫(xiě)字節(jié)字符串,它們都是&[u8;N]。
通常特殊字符用反斜杠字符進(jìn)行轉(zhuǎn)義:\。通過(guò)這種方式,您可以將任何字符添加到您的字符串中,甚至是不可打印的字符和您不知道如何鍵入的字符。如果你想要一個(gè)文字反斜杠,用另一個(gè)轉(zhuǎn)義:\
字符串或字符文字分隔符出現(xiàn)在文字中必須轉(zhuǎn)義:""",’\ "。
有時(shí)需要轉(zhuǎn)義的字符太多了,或者按原樣寫(xiě)出字符串會(huì)更方便。這就是原始字符串文字發(fā)揮作用的地方。
fn main() {let raw_str = r"Escapes don't work here: \x3F \u{211D}";println!("{}", raw_str);// If you need quotes in a raw string, add a pair of #slet quotes = r#"And then I said: "There is no escape!""#;println!("{}", quotes);// If you need "# in your string, just use more #s in the delimiter.// There is no limit for the number of #s you can use.let longer_delimiter = r###"A string with "# in it. And even "##!"###;println!("{}", longer_delimiter); }想要一個(gè)非UTF-8的字符串嗎?(記住,str和String必須是有效的UTF-8)。或者您想要一個(gè)字節(jié)數(shù)組,其中大部分是文本? yte strings字節(jié)字符串來(lái)拯救!
use std::str;fn main() {// Note that this is not actually a `&str`let bytestring: &[u8; 21] = b"this is a byte string";// Byte arrays don't have the `Display` trait, so printing them is a bit limitedprintln!("A byte string: {:?}", bytestring);// Byte strings can have byte escapes...let escaped = b"\x52\x75\x73\x74 as bytes";// ...but no unicode escapes// let escaped = b"\u{211D} is not allowed";println!("Some escaped bytes: {:?}", escaped);// Raw byte strings work just like raw stringslet raw_bytestring = br"\u{211D} is not escaped here";println!("{:?}", raw_bytestring);// Converting a byte array to `str` can failif let Ok(my_str) = str::from_utf8(raw_bytestring) {println!("And the same as text: '{}'", my_str);}let _quotes = br#"You can also use "fancier" formatting, \like with normal raw strings"#;// Byte strings don't have to be UTF-8let shift_jis = b"\x82\xe6\x82\xa8\x82\xb1\x82"; // "ようこそ" in SHIFT-JIS// But then they can't always be converted to `str`match str::from_utf8(shift_jis) {Ok(my_str) => println!("Conversion successful: '{}'", my_str),Err(e) => println!("Conversion failed: {:?}", e),}; }總結(jié)
以上是生活随笔為你收集整理的rust(54)-字符串的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: rust(53)-智能指针
- 下一篇: SSM框架中mapper和mapping