Skip to content

Instantly share code, notes, and snippets.

@max-itzpapalotl
Last active January 14, 2024 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max-itzpapalotl/b2a918f9bfa5a3dd3cadb301f27b4fa6 to your computer and use it in GitHub Desktop.
Save max-itzpapalotl/b2a918f9bfa5a3dd3cadb301f27b4fa6 to your computer and use it in GitHub Desktop.
15. String manipulation

15. String manipulation

Converting to strings

fn main() {
    let b = b"abc\xc3\xa4\xc3\xb6\xc3\xbc";
    let s = std::str::from_utf8(&b[0..9]);
    println!("Result: {:?}", s);
}

Will get UTF-8 error when slicing only &b[0..6].

fn main() {
    let s = "abcäöü";    // or with .to_string() as String
    let ss = &s[0..9];
    println!("Result: {:?}", ss);
}

Will get UTF-8 panic when slicing only &s[0..6].

Indexing

fn main() {
    let s = "abcäöü".to_string();
    // let c = s[4 as usize];     // not supported because of UTF-8 trouble
    let c = s.as_bytes()[4 as usize];
    println!("Result: {:x}", c);
}

Indexing into strings is not supported, need to use as_bytes().

fn main() {
    let s = "abcäöü".to_string();
    let c = s.chars().nth(3);
    println!("Result: {:?}", c);
}

Can use the iterator provided by chars().

fn main() {
    let s = "abcäöü".to_string();
    for c in s.chars() {
        println!("Result: {:?}", c);
    }
}

String concatenation

fn main() {
    let mut s = String::with_capacity(100);
    s = s + "abc";
    let t = "xyz".to_string();
    // s = s + t;   // does not work
    s = s + &t;     // works!
    s.push('X');
    // s.push_str(t);   // does not work
    s.push_str(&t);     // works
    println!("{}", s);
    // let u : String = s + &t;   // works, but moves s into u!
    let u : String = s.clone() + &t;
    println!("{} {}", s, u);
}

If there is enough capacity, there is no reallocation and memory copy.

String and &str methods

fn main() {
    // Matching:
    let s = "abcdefGhijklmnopqrstuvwxyz".to_string();
    if s.starts_with("abc") {
        println!("starts with abc");
    }
    if s.ends_with("xyz") {
        println!("ends with xyz");
    }

    // Finding:
    let mut pos = s.find("def");
    println!("def: {:?}", pos);
    pos = s.find('h');
    println!("h {:?}", pos);
    pos = s.find(char::is_uppercase);
    println!("is_uppercase: {:?}", pos);

    // Safe slicing:
    let r = s.get(6..9);
    println!("{:?}", r);
    let (a, b) = s.split_at(13);
    println!("{}, {}", a, b);

    // Splitting:
    let x = "abc def ghi".to_string();
    let pieces : Vec<&str> = x.split_whitespace().collect();
    println!("{:?}", pieces);
    let y = "abc\ndef\nghi\n\n".to_string();
    let pieces : Vec<&str> = y.lines().collect();
    println!("{:?}", pieces);

    // Trimming:
    let z = "   a b c  \n";
    println!("Trimmed:{}<<<", z.trim());
}

There is more: Repeating strings, replacing substrings, converting to upper or lower case, parsing to another type, ...

References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment