LoginSignup
9
5

More than 5 years have passed since last update.

Rust で文字列の n 文字目の文字を取得

Last updated at Posted at 2016-12-28

Rust では文字列の n 文字目を取る場合は一旦 .chars で文字にバラす必要がある(.chars はイテレータを返すだけなのでほぼオーバーヘッドは無い)

let s = "abcdef";
let c = s.chars().nth(2);
assert_eq!(c, Some('c'));

バイト単位でなく文字単位でのアクセスなので,n 文字目にアクセスするには前から順に1文字ずつ手繰る必要があり O(n) かかるっぽい.バイト単位で良いなら [u8] とかにばらしてからアクセスすれば O(1) になる.

.nth は添字と引数の値が1ずれるので注意. すみませんズレてませんでした…勘違いした.

9
5
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
9
5