生成设定长度的字符串

时间:2014-12-10 17:03:41

标签: string rust

我试图生成一个字符串,如果有[16,24 ..]列表和另一个列表[" 00"," 7F&#34 ; ..]

生成的列表是 [00000000000000000000000000000000,7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F7F,......

在python中

代码将是:

    for l in range(16, 32 + 1, 8):
        for b in ['00', '7f', '80', 'ff']:
          do_something(b * l);

我不确定如何在生锈中实现这一点,到目前为止,我已经得到了:

for &i in [16u,24u,32u].iter() {
    for n in ["00","7f","80","ff"].iter() {

    }
}

但我不知道如何创建字符串。

1 个答案:

答案 0 :(得分:4)

您可以使用std::str::StrAllocating::repeat

fn main() {
    for &i in [16u, 24u, 32u].iter() {
        for n in ["00", "7f", "80", "ff"].iter() {
            println!("{}", n.repeat(i))
        }
    }
}

打印

00000000000000000000000000000000
7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f
80808080808080808080808080808080
ffffffffffffffffffffffffffffffff
000000000000000000000000000000000000000000000000
7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f
808080808080808080808080808080808080808080808080
ffffffffffffffffffffffffffffffffffffffffffffffff
0000000000000000000000000000000000000000000000000000000000000000
7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f
8080808080808080808080808080808080808080808080808080808080808080
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff

Demo