【问题标题】:How to generate random unicode strings in rust?如何在 rust 中生成随机 unicode 字符串?
【发布时间】:2021-03-25 17:53:42
【问题描述】:

我正在实现一个模糊器,我想生成随机的 unicode 字符串。我想出了这个解决方案,但是,它的效率非常低,并且很少产生一些字符串。有没有更好的方法来生成 unicode 字符串?

谢谢。

use rand::{thread_rng, Error, Rng};
use std::convert::TryFrom;

fn main() -> Result<(), Error> {
    let mut rng = thread_rng();
    let mut arr: Vec<u32> = vec![0; 1024];
    rng.try_fill(&mut arr[..])?;

    println!(
        "{:?}",
        arr.iter()
            .map(|u| char::try_from(*u))
            .flatten()
            .collect::<String>()
    );

    Ok(())
}

Rust Playground link

【问题讨论】:

标签: random unicode rust


【解决方案1】:

使用这样的东西:

fn get_random_string(len: usize) -> String {
    rand::thread_rng()
        .sample_iter::<char, _>(rand::distributions::Standard)
        .take(len)
        .collect()
}

Playground

如果您想打印控制字符,您可能需要过滤控制字符。此外,字符分布与您在野外可能遇到的任何 UTF-8 字符串都非常不同。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-13
  • 2010-09-10
  • 2011-01-09
相关资源
最近更新 更多