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_owned(); // `.to_string()` also ok
let back_to_str = string_type1.as_str();
let raw_string = r#"
    {
        "name": "John Doe",
        "age": 43,
    }"#;

To create a new String from existing values, 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).
splitSplits a string slice by one or more characters.
split_whitespaceSplits a string slice by any amount of whitespace.
clearTruncates this String, removing all contents.
push_strAppends a given string slice onto the end of this String.

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();

Split by space and remove empty values:

rust
let values: Vec<String> = line
    .split_whitespace()
    .map(|s| s.to_owned())
    .collect();

Convert to number

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

Matching

Given an owned String, match its values with:

rust
match text.as_str() {
    "true" => true,
    "false" => false,
    _ => panic!("Expected true or false");
}

Update without assign

If updating a String in a function that received it as &mut, reassigning do not work.

rust
fn update_string(&mut s) {
    // Instead of:
    // s = String::from("New string");
    // Do:
    s.clear();
    s.push_str("New string");
}