gpt4 book ai didi

rust - Rust:最有效的方式来遍历ASCII字符串的字符

转载 作者:行者123 更新时间:2023-12-03 11:40:58 26 4
gpt4 key购买 nike

我原来的方法:

pub fn find_the_difference(s: String, t: String) -> char {
let mut c:u8 = 0;
for i in 0..s.chars().count() {
c ^= t.chars().nth(i).unwrap() as u8 ^ s.chars().nth(i).unwrap() as u8;
}
return (c ^ t.chars().nth(s.chars().count()).unwrap() as u8) as char;

}
但这太慢了,而且还很疯狂,我替换了 t[i] ^ s[i]所需要编写的所有内容(请参见下面的原始C++函数)。因此,我寻找其他东西,找到了 this method,我们在其中将字符串转换为char数组,并获得了一些不错的结果(从8ms变为0ms)。
pub fn find_the_difference(s1: String, t1: String) -> char {
let mut c:u8 = 0;
let s: Vec<char> = s1.chars().collect();
let t: Vec<char> = t1.chars().collect();

for i in 0..s1.chars().count() {
c ^= t[i] as u8 ^ s[i] as u8;
}
return (c ^ t[s1.chars().count()] as u8) as char;

}
但是也许不需要收集,也不必关心索引,我只想迭代一个字符。我目前的尝试:
pub fn find_the_difference(s1: String, t1: String) -> char {
let mut c:u8 = 0;
let mut s = s1.chars();
let mut t = t1.chars();
let n = s.count();

for i in 0..n {
c ^= t.next().unwrap() as u8 ^ s.next().unwrap() as u8; // c ^= *t++ ^ *s++ translated in C++
}
return (c ^ t.next().unwrap() as u8) as char;

}
我收到以下错误消息:
Line 9, Char 44: borrow of moved value: `s` (solution.rs)
|
4 | let mut s = s1.chars();
| ----- move occurs because `s` has type `std::str::Chars<'_>`, which does not implement the `Copy` trait
5 | let mut t = t1.chars();
6 | let n = s.count();
| - value moved here
...
9 | c ^= t.next().unwrap() as u8 ^ s.next().unwrap() as u8;
| ^ value borrowed here after move
error: aborting due to previous error
是否可以实现这种代码 c = *t++
注意:s1.chars.count()= t1.chars.count()-1,目标是在t1中找到多余的字母
NB2:原始的C++函数:
char findTheDifference(string s, string t) {
char c = 0;
for (int i = 0; t[i]; i++)
c ^= t[i] ^ s[i];
return c;
}

最佳答案

我认为您对C和Rust字符串处理之间的区别以及Rust的strString&[u8]charu8类型之间的区别感到困惑。
就是说,这就是我实现您的功能的方式:

fn find_the_difference(s: &[u8], t: &[u8]) -> u8 {
assert!(t.len() > s.len());
let mut c: u8 = 0;
for i in 0..s.len() {
c ^= s[i] ^ t[i];
}
c ^ t[s.len()]
}
如果您的数据当前为 String,则可以使用 &[u8]方法获取其数据的 as_bytes() View 。像这样:
let s: String = ...some string...;
let t: String = ...some string...;

let diff = find_the_difference(s.as_bytes(), t.as_bytes());

关于rust - Rust:最有效的方式来遍历ASCII字符串的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66590759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com