String examples

Creation:

fn main() {
    let s: String = String::from("a string");
    println!("s = {s}");
}

Length:

fn main() {
    let s: String = String::from("a string");
    println!("len = {}", s.len());
}

Concatenation:

fn main() {
    let mut s: String = String::from("123");
    s += "456";
    s.push_str("789");
    s.push('0');
    println!("{s}");
}

Subslice:

fn main() {
    let s: String = String::from("ABCDEFG");
    println!("{}", &s[1..3]);
}

str type:

fn main() {
    let s: String = String::from("ABCDEFG");
    let slice: &str = &s[1..3];
    println!("{}", slice);
}

Problems

At the end, upload all the problems below to a GitHub repository under a folder named lab02.

P1

Create a function named add_chars_n which will take tree arguments (the string, the char, and the number), and returns a string with n characters added to the end of the string. The following main function to compile:

fn main() {
    let mut s = String::from("");
    let mut i = 0;
    while i < 26 {
        let c = (i as u8 + b'a') as char;
        s = add_chars_n(s, c, 26 - i);

        i += 1;
    }

    print!("{}", s);
}

P2

Rewrite the previous code so that the function takes a reference to a string and doesn't return anything.

P3

Write the following functions; they all take a string as first argument in whichever form you like:

  • add_space: concatenates n spaces to the string
  • add_str: concatenates a str to the string
  • add_integer: concatenates an integer to the string. Add separators at every 3 digits.
  • add_float: concatenates a float to the string

You must do the conversion from the numbers to the string by hand, without any help from std.

Call all the above functions as many times as you want in order to create the following string exactly. Do not use add_str with any constant spaces. Print the result to the terminal.

                                        I 💚
                                        RUST.

    Most            crate      306_437_968           and     lastest         is
         downloaded        has             downloads     the         version    2.038.