// Push string str.push_str("ust"); // capacity is doubled to 12 println!("Now str: {}", str);
// Check if empty println!("Is empty: {}", str.is_empty());
// Check if contains println!("Contains 'PHP'? {}", str.contains("PHP"));
// Replace substring with println!("Replace output: {}", str.replace("Rust", "Solana")); // replace is not a in-place operation // so value of str is still "Hello Rust"
// Iterate a string by word (whitespace) forwordinstr.split_whitespace() { println!("{}", word); }
// Create a string with capacity letstr_with_cap_10 = String::with_capacity(10); println!("Length: {} Capacity: {}", str_with_cap_10.len(), str_with_cap_10.capacity()); }
The above outputs the following:
1 2 3 4 5 6 7 8 9 10
Now str: Hello Length: 6 Capacity: 6 Now str: Hello R Now str: Hello Rust Is empty: false Contains 'PHP'? false Replace output: Hello Solana Hello Rust Length: 0 Capacity: 10
Use “+” to append string
1 2 3 4
lets1 = String::from("Hello"); lets2 = String::from(" Rust"); lets3 = s1 + &s2; // Note: s1 is no longer valid since it's ownership is moved to s3 // s3 = "Hello Rust"