日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

rust(54)-字符串

發布時間:2025/3/12 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 rust(54)-字符串 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Rust有兩種類型的字符串:String 和&str。
String 存儲為字節向量(Vec),但保證始終是有效的UTF-8序列。字符串是堆分配的,可增長的,不以空null 結束。
&str是一個切片(&[u8]),它總是指向一個有效的UTF-8序列,并且可以用來查看String,就像&[T]是Vec的一個視圖一樣。

fn main() {// (all the type annotations are superfluous)// A reference to a string allocated in read only memorylet pangram: &'static str = "the quick brown fox jumps over the lazy dog";println!("Pangram: {}", pangram);// Iterate over words in reverse, no new string is allocatedprintln!("Words in reverse");for word in pangram.split_whitespace().rev() {println!("> {}", word);}// Copy chars into a vector, sort and remove duplicateslet mut chars: Vec<char> = pangram.chars().collect();chars.sort();chars.dedup();// Create an empty and growable `String`let mut string = String::new();for c in chars {// Insert a char at the end of stringstring.push(c);// Insert a string at the end of stringstring.push_str(", ");}// The trimmed string is a slice to the original string, hence no new// allocation is performedlet chars_to_trim: &[char] = &[' ', ','];let trimmed_str: &str = string.trim_matches(chars_to_trim);println!("Used characters: {}", trimmed_str);// Heap allocate a stringlet alice = String::from("I like dogs");// Allocate new memory and store the modified string therelet bob: String = alice.replace("dog", "cat");println!("Alice says: {}", alice);println!("Bob says: {}", bob); }

有多種方法可以編寫包含特殊字符的字符串字面值。所有的結果都是一個相似的&str,所以最好使用最方便書寫的表單。類似地,也有多種方法來編寫字節字符串,它們都是&[u8;N]。
通常特殊字符用反斜杠字符進行轉義:\。通過這種方式,您可以將任何字符添加到您的字符串中,甚至是不可打印的字符和您不知道如何鍵入的字符。如果你想要一個文字反斜杠,用另一個轉義:\
字符串或字符文字分隔符出現在文字中必須轉義:""",’\ "。

fn main() {// You can use escapes to write bytes by their hexadecimal values...let byte_escape = "I'm writing \x52\x75\x73\x74!";println!("What are you doing\x3F (\\x3F means ?) {}", byte_escape);// ...or Unicode code points.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 literalscan span multiple lines.The linebreak and indentation here ->\<- can be escaped too!";println!("{}", long_string); }

有時需要轉義的字符太多了,或者按原樣寫出字符串會更方便。這就是原始字符串文字發揮作用的地方。

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); }

想要一個非UTF-8的字符串嗎?(記住,str和String必須是有效的UTF-8)。或者您想要一個字節數組,其中大部分是文本? yte strings字節字符串來拯救!

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),}; }

總結

以上是生活随笔為你收集整理的rust(54)-字符串的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。