How to swap two char in String in Rust

Viewed 252

I am trying swap two chars in a String. Here is My Code, I guess there must be a better way to do this.

pub fn swap(s: &String, from_idx: usize, to_idx: usize) -> String {
   let a = s.clone().chars().nth(from_idx).unwrap();
   let b = s.clone().chars().nth(to_idx).unwrap();
   let mut result = s.clone();
   result.replace_range(from_idx..from_idx + 1, &b.to_string());
   result.replace_range(to_idx..to_idx + 1, &a.to_string());
   return result;
}

Is there a better way, such as shorter syntax or better perfomance?

1 Answers

My approach would be:

pub fn swap(s: &str, from_idx: usize, to_idx: usize) -> String {
   // create a Vec of all characters
   let mut chars: Vec<_> = s.chars().collect();
   // swap the characters in the Vec
   chars.swap(from_idx, to_idx);
   // convert Vec back to String
   chars.into_iter().collect()
}
Related