比较 Rust 中的字符串 [英] Comparing string in Rust

查看:622
本文介绍了比较 Rust 中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较从 stdin 输入的字符串与没有运气的静态字符串.

I want to compare a string input from stdin to a static string with no luck.

这是我迄今为止尝试过的:

Here is what I have tried so far:

fn main() -> () {
    let mut line = "".to_string();
    let exit = "exit".to_string(); 

    while line.as_slice() != exit.as_slice() {
        let input = std::io::stdin().read_line().ok();

        line.push_str( input.unwrap().to_string().as_slice() );

        assert_eq!(line, exit);
    }   
}

但是在断言期间它失败了.我应该如何将字符串输入与 Rust 中的静态字符串进行比较?

However during assertion it failed. How should I compare a string input to a static string in Rust?

非常感谢您的帮助.

推荐答案

首先,该行包含行终止符.您可能想使用 trim(或其变体之一)来忽略它.

First of all, the line contains the line terminator. You probably want to use trim (or one of its variants) to ignore that.

其次,您进行了大量不必要的转换和分配.尽量避免这些.

Secondly, you're doing a lot of unnecessary conversions and allocations. Try to avoid those.

第三,由于过度分配,to_string(或者至少,我最后一次检查)效率低下.你想要into_string.

Third, to_string is (or at least, was the last time I checked) inefficient due to over-allocation. You want into_string.

第四,从 String&str 的最快方法是交叉借用"它;给定一个 String s&*s 会将它作为 &str 重新借用.这是因为 String 实现了 Deref<&str>;换句话说,String 的作用有点就像一个指向借用字符串的智能指针,允许它衰减成更简单的形式.

Fourth, the quickest way to go from a String to a &str is to "cross-borrow" it; given a String s, &*s will re-borrow it as a &str. This is because a String implements Deref<&str>; in other words, String acts kind of like a smart pointer to a borrowed string, allowing it to decay into a simpler form.

第五,除非您正在做一些不寻常的事情,否则您可以使用 lines 迭代器方法将其重写为 for 循环.

Fifth, unless you're doing something unusual, you can rewrite this as a for loop using the lines iterator method.

第六,请注意 stdin() 实际上每次调用时都会分配一个新的缓冲读取器.不仅如此,当创建新缓冲区时,读入缓冲区的字符不会被推回"到标准输入中;该数据只是丢失了.所以你真的不想在循环中调用它.如果需要,请调用一次并将结果保存在变量中.

Sixth, be aware that stdin() actually allocates a new buffered reader every time you call it. Not only that, but characters read into the buffer do not get "pushed back" into STDIN when a new buffer is created; that data is simply lost. So you really don't want to be calling it in a loop. If you need to, call it once and keep the result in a variable.

所以,我最终得到了这个:

So, I end up with this:

fn main() {
    for line in std::io::stdin().lines() {
        // Extract the line, or handle the error.
        let line = match line {
            Ok(line) => line,
            Err(err) => panic!("failed to read line: {}", err)
        };

        assert_eq!(line.trim(), "exit");
    }
}

这篇关于比较 Rust 中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆