0
1

Rustでpythonのように文字列をスライスしよう

Posted at

Rustでpythonのように文字列をスライスしたい

Python使いがRustでハマる文字列スライス

RustにはPythonのように

data = "これはテストです。"
print(data[0:2])
# "これ"が出力される

便利な日本語を直感的に文字列スライスするような関数は用意されていません。
最初、この仕様でハマっていました。やり方も一度StringをChar型に変換してfor文で回すという面倒なやり方でやっていました。

トレイトとの出会い

トレイトの使い方がよく分からず、関数とStructで逃げていましたがUdemyのRustコース(英語)をtrait部分を受講・写経しているときに天啓が降りてきて、Rustの文字列はいつも同じやり方をしています。

具体的なコードは以下の様な感じ


// pythonライクなトレイト(属性・性質)を定義
trait PythonLikeSlice {
    fn slice(&self,from:usize,to:usize) -> String;
}

// 次にString型に直にPythonLikeSliceを実装
impl PythonLikeSlice for String {
    // pythonで言うdata[0..5]に近いやり方を定義
    fn slice(&self,from:usize,to:usize) -> String {
    
        let mut slice_string = String::from("");
    
        for (i, c )in self.chars().enumerate(){
            if from <= i && i < to {
                slice_string.push(c);
            }
        }

        slice_string
    }
}

fn main(){
    // Pythonライクなスライスができる。
    let original_string = String::from("test_string");
    let changed_string = original_string.slice(0, 4);

    println!("{}",changed_string);
    // "test"が出力されます。

}

いつもこのやり方をやっています。
自分用の備忘録用に残しておきます。

0
1
0

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
0
1