2

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?

3
  • Although not a duplicate, you might also find more information at this answer Commented Dec 8, 2021 at 13:06
  • “Is there a better way” Yes. Swapping Unicode Scalar Values makes little to no sense. You probably shouldn't be using a string in the first place. Commented Dec 8, 2021 at 14:31
  • Note also that the code in question is swapping bytes, not chars. So it will panic if characters on the provided indices are not ASCII - play.rust-lang.org/…. Commented Dec 8, 2021 at 15:55

1 Answer 1

3

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() } 
Sign up to request clarification or add additional context in comments.

6 Comments

thank you, Now I know Vec has the swap method can do the trick
This will seem to work on simple strings with simple Unicode, but not in general. Swapping Unicode Scalar Value makes no sense. There's almost no correct use for str::chars.
@hackape swapping characters 0 and 2 in this string: èa (yes it contains three characters) will give àe (probably not what you expect)
Here's a playground that illustrates my previous comment.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.