简体   繁体   中英

Most idiomatic way to double every character in a string in Rust

I have a String , and I want to make a new String , with every character in the first one doubled. So "abc" would become "aabbcc" and so on.

The best I've come up with is:

let mut result = String::new();
for c in original_string.chars() {
    result.push(c);
    result.push(c);
}
result

This works fine. but is there a more succinct (or more idiomatic) way to do this?

In JavaScript I would probably write something like:

original.split('').map(c => c+c).join('')

Or in Ruby:

(original.chars.map { |c| c+c }).join('')

Since Rust also has functional elements, I was wondering if there is a similarly succinct solution.

I would use std::iter::repeat to repeat every char value from the input. This creates an infinite iterator, but for your case we only need to iterate 2 times , so we can use take to limit our iterator, then flatten all the iterators that hold the doubled char s.

use std::iter;

fn main() {
    let input = "abc"; //"abc".to_string();

    let output = input
        .chars()
        .flat_map(|c| iter::repeat(c).take(2))
        .collect::<String>();

    println!("{:?}", output);
}

Playground

Note: To double we are using take(2) but you can use any usize to increase the repetition.

Personally, I would just do exactly what you're doing. Its intent is clear (more clear than the functional approaches you presented from JavaScript or Ruby, in my opinion) and it is efficient. The only thing I would change is perhaps reserve space for the characters, since you know exactly how much space you will need.

let mut result = String::with_capacity(original_string.len() * 2);

However, if you are really in love with this style, you could use flat_map

let result: String = original_string.chars()
    .flat_map(|c| std::iter::repeat(c).take(2))
    .collect();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM