How to mutate String

I'd like to replace ?,;!'. chars in a String with space.
I found as_bytes() as_mut_str() as_mut_ptr() fns, but it seems that these methods didn't work.
I also found replace() fn, but I don't understand what its Pattern parameter means.
Is it idiomatic to mutate a String or create a new String?

There is a documentation for pattern at the split method.

Pattern can either be

  • a char, e.g. 'c'
  • a &str, e.g. "abc"
  • a closure, e.g. |x| x == 'c' && x == 'f'
  • a slice of chars, e.g. &['c', 'f', '3']

so for your case I would go with the closure:

let a = "AB)?,:;!das";
dbg!(a.replace(
    |c| match c {
        '?' | ',' | ';' | '!' | '\'' | '.' => true,
        _ => false,
    },
    " "
));

(See Post #3 for a better solution)

2 Likes

Actually, an array of chars also works and is more readable in this case:

a.replace(['?', ',', ';', '!', '\'', '.'].as_ref(), " ")
3 Likes

You're totaly right. I totally forgot about the char array impl. Dang :smiley: