Problem Solving Preparation
Let's look at some helpful methods that will help you in solving coding problems on strings.
Convert String to &str
let string = String::from("Hello World");
let slice = string.as_str();
Convert &str to String
let slice = "Hello World";
let string = slice.to_string();
Create a String with given values
#![allow(unused)] fn main() { let name = "Hashirama"; let dialogue = format!("I've been waiting for you, {}!", name); println!("{dialogue}"); }
Replace a slice or a character in a string
#![allow(unused)] fn main() { let mut sentence = "mife is movemy"; let new_sentence = sentence.replace("m", "l"); println!("{new_sentence}"); }
Convert a &str into Vec
If you want to access individual values in a string slice, it is better to convert it into a vector of chars
let my_str: &str = "123456789";
let char_vec: Vec<char> = my_str.chars().collect();
The chars
method returns an iterator over the individual characters of the slice and the collect
method takes the characters and turn them into a collection.
Access nth character in a string
The nth()
is used to return the nth element of the iterator. This means nth
must be used with an iterator or in case of a string, chars()
.
#![allow(unused)] fn main() { let my_str: &str = "Secret no: 4"; let num = my_str.chars().nth(11).unwrap(); println!("{num}"); }
Split a string
The split
1 method in Rust is used to divide a string slice into an iterator of substrings based on a specified delimiter.
#![allow(unused)] fn main() { let v: Vec<&str> = "Mary had a little lamb".split(' ').collect(); assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]); }