【发布时间】:2015-04-10 02:42:10
【问题描述】:
如何通过索引访问借用字符串中的元素?
在 Python 中直截了当:
my_string_lst = list(my_string)
print my_string_list[0]
print my_string[0] # same as above
生锈(尝试 1):
let my_string_vec = vec![my_string]; # doesn't work
println!("{}", my_string_vec[0]); # returns entire of `my_string`
生锈(尝试 2):
let my_string_vec = my_string.as_bytes(); # returns a &[u8]
println!("{}", my_string_vec[0]); # prints nothing
我的最终目标是将它放入这样的循环中:
for pos in 0..my_string_vec.len() {
while shift <= pos && my_string_vec[pos] != my_string_vec[pos-shift] {
shift += shifts[pos-shift];
}
shifts[pos+1] = shift;
}
for ch in my_string_vec {
let pos = 0; // simulate some runtime index
if my_other_string_vec[pos] != ch {
...
}
}
我认为可以在我的条件语句中使用my_string_vec.as_bytes()[pos]和my_string_vec.as_bytes()[pos-shift],但我觉得这有一种不好的代码味道。
【问题讨论】:
标签: rust