迭代一组字符串并将它们连接起来
所以我有一个代码,它不断地要求输入,然后将您的输入作为 shell 命令执行。我知道我从 shell 命令获得的输出位于某种缓冲区中。然而,现在,由于有许多命令会输出大量行,因此我希望将所有输出都放入一个字符串中。
extern crate subprocess;
use std::io;
use std::io::{BufRead, BufReader};
use subprocess::Exec;
fn main() {
loop {
let mut mycommand_string: String = String::new();
io::stdin()
.read_line(&mut mycommand_string)
.expect("Failed to read line");
let mycommand: &str = &*mycommand_string;
let x = Exec::shell(mycommand).stream_stdout().unwrap();
let br = BufReader::new(x);
let full: String = " ".to_string();
let string = for (i, line) in br.lines().enumerate() {
let string: String = line.unwrap().to_string();
let full = format!("{}{}", full, string);
println!("{}", full);
};
println!("{}", string);
}
}
这是我的代码。正如您所看到的,我的目标是以某种方式迭代 br.lines() ,并为其包含的每一行输出,将其附加或连接到一个字符串,以便所有输出以一个字符串结束,最好在每一行之间有 "\n"
,但不是必需的。
具体来说,我想迭代变量 br
的结果,该变量的类型我不理解,并将所有字符串连接在一起。
So I have a code which constantly asks for input and then executes your input as a shell command. I understand that the output I am getting from the shell commands is in a buffer of some sort. Now, however, as there are many commands which output lots of lines, I would like to get all of the output into one single string.
extern crate subprocess;
use std::io;
use std::io::{BufRead, BufReader};
use subprocess::Exec;
fn main() {
loop {
let mut mycommand_string: String = String::new();
io::stdin()
.read_line(&mut mycommand_string)
.expect("Failed to read line");
let mycommand: &str = &*mycommand_string;
let x = Exec::shell(mycommand).stream_stdout().unwrap();
let br = BufReader::new(x);
let full: String = " ".to_string();
let string = for (i, line) in br.lines().enumerate() {
let string: String = line.unwrap().to_string();
let full = format!("{}{}", full, string);
println!("{}", full);
};
println!("{}", string);
}
}
This is my code. As you can see, the thing I am aiming for is to somehow iterate over br.lines()
and for each line of output it contains, append or concatenate it to a string, so that all the output ends up in one single string, preferably with "\n"
in between each line, but not neccesarilly.
Specifically I would like to iterate over the result of the variable br
which has a type I dont understand and to concatenate all the strings together.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您有一个行迭代器,那么您可以简单地将其收集到一个字符串中:
当然,我们不应该忽视这样做似乎没有很多可能的原因......
If you have an iterator of lines, then you can simply collect that into a string:
Of course we should not ignore that there do not seem to be many possible reasons for ever doing that...