How can I swap parts of a string? rust

let mut hour = "sss"
let mut min = "lll"

I want to swap hour[0] as string and min[1] as string, how can I do that?

1 Like

Assuming you meant you want the code to also work for swapping larger ranges than just one character, you can do it like this


fn main() {
    // Need `to_string` so we can mutate the values.
    let mut hour = "sss".to_string();
    let mut min = "lll".to_string();

    let min_range = 1..2;
    let hour_range = 0..1;
    // Have to get a copy of the data since we're about to mutate `min`.
    let min_removed = String::from(&min[min_range.clone()]);
    min.replace_range(min_range, &hour[hour_range.clone()]);
    hour.replace_range(hour_range, &min_removed);

    assert_eq!(&hour, "lss");
    assert_eq!(&min, "lsl");

Strings in Rust are Unicode, and in Unicode "characters" (grapheme clusters) have variable width (not just UTF-8 bytes, but also various ligatures and sequences of decomposed diacritics and multi-codepoint emoji). In general case it's not possible to swap them without possibly moving rest of the string.

I suggest trying a different approach, and perhaps making new strings from scratch instead.

If you want to work with ASCII strings and treat them as a bunch of bytes, there's: