It seems that every programming language has to have its own special string way. Rust is not an exception. But at least strings in Rust are UTF-8 as expected and they are not complete aliens. In general, C++ programmers will not be surprised that much, others like Java developers will have to get used to some limitations.
First string type is &’static str. It’s statically allocated inside compiled program.
let hello = “Hello, this is Rust &‘static str”;
The second type is dynamic String type which is heap-allocated.
let s = “Hello, this will be String type”.to_string();// orlet s = String::from(“Hello, this will be String type”);
String concatenation
For higher level language developers, some constructions just don’t work like simple combining two strings. It’s because type mismatch for expected operands here and Rust is quite strict in this cases.
// these don't work
let s: String = “Hello”; // cannot assign str to Stringlet s1: String = String::from(“Hello “);
let s2: String = String::from(“ world”);
let s3: String = s1 + s2; // cannot add String to String like this
String concatenation with + operator is possible when one first operand is string and second is str;
let str1 = "Hello ".to_string();
let str2 = "world!";
let concat = str1 + str2;
or with two strings by using string coerce between &String and &str.
let str1 = "Hello ".to_string();
let str2 = "world!".to_string();
let concat = str1 + &str2;
To have mutable string, mut must be added as expected
let mut mutableString = "Hello Rust (rev1)";
mutableString = "Hello Rust (rev2)";
Passing strings into functions
There is no surprise, usage is quite as expected.
fn display_string(str: String) {
println!("{}",str);
}// in main method
display_string("Print this".to_string);
or by using str/&str or &mut str
fn display_str(str: &str) {
println!("{}",str);
}// in main method
display_string("Print this");
Substring
Second line below returns first 5 bytes
let hello_world = “Hello World”;
let hello = &hello_world[0..5];
println!("{}",hello);
Be careful, this above works with bytes, not with chars (which can be multi-byte), but safely we can read byte by byte
let notes = "♫♫♫♫♫♫♫";
for b in notes.as_bytes() {
print!("{}, ", b);
}// output: 226, 153, 171, 226, 153, 171, 226, 153, 171, 226, 153, 171, 226, 153, 171, 226, 153, 171, 226, 153, 171,
or char by char
let notes = "♫♫♫♫♫♫♫";for note in notes.chars() {
print!("{}, ", note);
}
// output: ♫, ♫, ♫, ♫, ♫, ♫, ♫,
Some other string methods
// create new String
let s = String::new();// create string from str
let s = String::from(“hi“);// push and pop char/string to and from string
s.push('a');
s.push_str("added");
s.pop();// remove char at byte position
s.remove(3);// string lenght in bytes
let strlen = s.len();// split string into two
let (first, last) = s.split_at(3);
There are many others string functions, see https://doc.rust-lang.org/std/string/struct.String.html