I want to create a function that takes a string and returns an array of versions of it in which always one pair of characters is transposed (swapped).
I came up with this:
fn transposes(s: &str) -> Vec<String> {
let mut vec = vec![];
let b = s.as_bytes();
for i in 1..b.len() {
let mut transpose = String::with_capacity(s.len());
transpose.push_str(&s[..i - 1]);
transpose.push(s.as_bytes()[i] as char);
transpose.push(s.as_bytes()[i - 1] as char);
transpose.push_str(&s[i + 1..]);
vec.push(transpose);
}
vec
}
fn main() {
let s = "maxi".to_owned();
println!("{:?}", transposes(&s));
}
Output is:
["amxi", "mxai", "maix"]
That result is what I want, it does:
- First swap
m
anda
- Then swap
a
andx
- Then swap
i
andx
I don't find the code super readable because of the string slicing going on. In C it would be a mere "pointer swap", but my Rust version looks a bit more involved.
Is there a better way to do what I want?
It is a fair assumption that this will only work correctly for ASCII strings.