Rust字符串使用
前言
在编程语言中,字符串的使用都是很频繁的,所以学习字符串的使用,也是不可缺少的.mut关键字let x = 64; x = 128; //修改变量x的值,在Rust中是无法编译通过 println!("{:?}", x);
看Rust编译提示:305 | let x = 64; | - | | | first assignment to `x` | help: make this binding mutable: `mut x` 306 | x = 128; | ^^^^^^^ cannot assign twice to immutable variable
在Rust中,默认变量是无法进行修改的.若需要修改变量x,则需要加上mut关键字.let mut x = 64; x = 128; //这样就可以编译通过 println!("{:?}", x);String常用的方法fn string_test() { let mut str = String::from("中文"); println!("str len = {}", str.len()); //长度为什么不是2,是因为utf-8编码,一个字符占用3个字节 println!("str count = {}", str.chars().count()); //count是用来获取字符串长度 let mut s = String::new(); s.push_str("hello"); s.push_str(" world"); println!("{:?}", s); let pos = s.find("w").unwrap_or(s.len()); //查找w在字符串中的位置 println!("{:?}", pos); s += " 123"; //字符串拼接 println!("{:?}", s); println!("point address:{:p}", s.as_ptr()); //获取字符串的指针 s = s.replace("w", ""); //字符串替换 println!("{:?}", s); println!("{:?}", s.contains("d")); //是否包含 }
个人能力有限,如果您发现有什么不对,请私信我
如果您觉得对您有用的话,可以点个赞或者加个关注,欢迎大家一起进行技术交流