Day16:String methods - 100DayOfRust
BC
Posted on December 2, 2019
This article will cover some common methods of String.
Code:
fn main() {
// integer to string
let num = 123;
let s = num.to_string();
println!("s is {}", s);
// string to integer
let num2 = s.parse::<i32>().unwrap();
println!("num2 is {}", num2);
// join
let strlist = vec!["hello", "world", "from", "rust"];
println!("joined: {}", strlist.join(", "));
// trim
let s = " Hello world ";
println!("trimmed: {} length: {}", s.trim(), s.trim().len());
// to lowercase
println!("lowercase: {}", s.to_lowercase());
// to upppercase
println!("uppercase: {}", s.to_uppercase());
// find
println!("find e: {:?}", s.find("e"));
println!("find d: {:?}", s.find("d"));
println!("find z: {:?}", s.find("z"));
// start & end with
let s = s.trim().to_lowercase();
println!("starts with: {}", s.starts_with("he"));
println!("ends with: {}", s.ends_with("ld"));
// replace
println!("replaced: {}", s.replace(" ", "##"));
// split
let splitted: Vec<&str> = s.split(" ").collect();
println!("Splitted: {:?}", splitted);
}
Result:
s is 123
num2 is 123
joined: hello, world, from, rust
trimmed: Hello world length: 11
lowercase: hello world
uppercase: HELLO WORLD
find e: Some(3)
find d: Some(12)
find z: None
starts with: true
ends with: true
replaced: hello##world
Splitted: ["hello", "world"]
Reference
💖 💪 🙅 🚩
BC
Posted on December 2, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.