LoginSignup
1
1

More than 3 years have passed since last update.

Rust Stringを逆にする

Posted at

0. 環境

  • rustc 1.38.0 (625451e37 2019-09-23)
  • binary: rustc
  • commit-hash: 625451e376bb2e5283fc4741caa0a3e8a2ca4d54
  • commit-date: 2019-09-23
  • host: x86_64-pc-windows-msvc
  • release: 1.38.0
  • LLVM version: 9.0

1. 経緯

Stringの文字列を逆にする関数を探しても上手いこと見つけられなかったので, 自作しました。

2. 作成したもの

fn reverse_string(input &String) -> String {
    let mut reversed = String::new();
    let mut chars: Vec<char> = Vec::new();

    for c in input.chars().into_iter() {
        chars.push(c);
    }

    for i in (0..chars.len()).rev() {
        reversed += &chars[i].to_string();
    }

    return reversed;
}

3. 使用例


fn reverse_string(input: &String) -> String {
    // 以下略
}

fn main() {
    let sample_string = String::from("test");
    let reversed_string = reverse_string(&sample_string);

    println!("{}", reversed_string);    // tset と表示される
}
1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1