7.字符串.rs
/**/fn test_1() {//新建字符串:let string = String::new();//字符串長度:let len = string.len();//基礎類型轉換成字符串:let one = 1.to_string(); // 整數到字符串let float = 1.3.to_string(); // 浮點數到字符串let slice = "slice".to_string(); // 字符串切片到字符串let my_int = one.parse::<i32>().unwrap();let my_float = float.parse::<f32>().unwrap();let my_slice = slice.as_str();
}//包含 UTF-8 字符的字符串:
fn test_2() {let hello = String::from("?????? ?????");let hello = String::from("Dobry den");let hello = String::from("Hello");let hello = String::from("???????");let hello = String::from("??????");let hello = String::from("こんにちは");let hello = String::from("?????");let hello = String::from("你好");let hello = String::from("Olá");let hello = String::from("Здравствуйте");let hello = String::from("Hola");
}//字符串追加:
fn test_3() {let mut s = String::from("run");s.push_str("oob"); // 追加字符串切片s.push('!'); // 追加字符println!("{}", s);
}//用 + 號拼接字符串:
fn test_4() {let s1 = String::from("Hello, ");let s2 = String::from("world!");let s3 = s1 + &s2;println!("{}", s3);
}//這個語法也可以包含字符串切片:
fn test_5() {let s1 = String::from("tic");let s2 = String::from("tac");let s3 = String::from("toe");let s = s1 + "-" + &s2 + "-" + &s3;println!("{}", s);
}//使用 format! 宏:
fn test_6() {let s1 = String::from("tic");let s2 = String::from("tac");let s3 = String::from("toe");let s = format!("{}-{}-{}", s1, s2, s3);println!("{}", s);
}//字符串長度:
fn test_7() {let s = "hello";let len = s.len(); //5let s = "你好";let len = s.len(); //這里 len 的值是 6。因為中文是 UTF-8 編碼的,每個字符長 3 字節,所以長度為6。let len = s.chars().count(); //如果想統計字符數量可以先取字符串為字符集合:let s = "hello你好";let len = s.chars().count();//7
}fn main() {test_1();test_2();test_3();test_4();test_5();test_6();test_7();
}
?
總結
- 上一篇: 6.变量的使用.rs
- 下一篇: 8.元组tup.rs