LANGUAGE » RUST

String

Constructor

There is the str (sequence of chars) and the String type.

rust
const GLOBAL_STR: &'static str = "Available globally";

let mystr = "Hello World";
let string_type1 = String::from(mystr);
let string_type2 = mystr.to_string();
let raw_string = r#"
    {
        "name": "John Doe",
        "age": 43,
    }"#;

To create new strings from existing strings, like f-string on python, format!() is very useful.

rust
let keyvalue_display = format!("{}={}", key, value);

Methods

MethodDescription
getSafer way to access index of the string.
is_emptyReturns true if the string has length of zero.
lenGet the length of the string in number of bytes.
linesAn iterator over the lines of a string, as string slices.
trimReturns a string slice with leading and trailing whitespace removed (includes \n).

Split

Split by lines:

rust
for line in file_contents.lines() {
    println("{}", line);
}

Split by a character and collect into a collection (array):

rust
let key_value: Vec<&str> = line.split('=').collect();

Convert to number

rust
let parsed: i32 = "5".parse().unwrap();
let turbo_parsed = "10".parse::<i32>().unwrap();