gpt4 book ai didi

recursion - 如何使用递归来反向转换Rust String?

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

当使用递归方式反转String时,我发现很难将String的一部分移到下一个,因为切片是&str类型而不是String
这不会运行:

fn reverse_string(s: &mut String) {
if s.is_empty() {
return;
}
// how to pass a correct parameter?
reverse_string(&mut s[1..]);
s.push(s.chars().nth(0).unwrap());
s.remove(0);
}
error[E0308]: mismatched types
--> src/lib.rs:6:20
|
6 | reverse_string(&mut s[1..]);
| ^^^^^^^^^^^ expected struct `String`, found `str`
|
= note: expected mutable reference `&mut String`
found mutable reference `&mut str`

最佳答案

Rust字符串为UTF-8,这意味着

  • 一个代码点没有固定长度的
  • 没有关于应该交换什么单位的定义。

  • 如果只想交换 ASCII字符串的字符,则可以这样做:
    use std::mem;

    fn reverse_string_ascii(s: &mut str) {
    if !s.is_ascii() {
    return;
    }

    // Safety: We have checked that the string is ASCII,
    // so it's fine to treat it as a slice of bytes.
    unsafe {
    fn rev(b: &mut [u8]) {
    match b {
    [] => {}
    [_] => {}
    [h, rest @ .., t] => {
    mem::swap(h, t);
    rev(rest)
    }
    }
    }

    rev(s.as_bytes_mut());
    }
    }

    fn main() {
    let mut s = String::from("hello");
    reverse_string_ascii(&mut s);
    println!("{}", s);
    }
    尽管这里没有真正的理由使用递归,但迭代更好:
    let mut todo = s.as_bytes_mut();
    loop {
    match todo {
    [] => break,
    [_] => break,
    [h, rest @ .., t] => {
    mem::swap(h, t);
    todo = rest;
    }
    }
    }
    也可以看看:
  • Why is capitalizing the first letter of a string so convoluted in Rust?
  • Reversing a string in Rust
  • 关于recursion - 如何使用递归来反向转换Rust String?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65702283/

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