2017-05-06 594 views

回答

0

您正在寻找String的find方法。要查找的'g'"Program"你可以做

"Program".find('g') 

Docs on find索引。

+0

感谢的人,现在我可以完成我的代码=) – MrCoder

2

虽然有点更令人费解比我想的,另一种解决方案是使用Chars迭代器及其position()功能:

"Program".chars().position(|c| c == 'g').unwrap() 

find在接受的解决方案使用返回字节偏移并不见得角色的索引。它适用于基本的ASCII字符串,比如问题中的字符串,并且在与多字节Unicode字符串一起使用时会返回一个值,将结果值视为字符索引会导致问题。

这工作:

let my_string = "Program"; 
let g_index = my_string.find("g"); // 3 
let g: String = my_string.chars().skip(g_index).take(1).collect(); 
assert_eq!("g", g); // g is "g" 

这不起作用:

let my_string = "プログラマーズ"; 
let g_index = my_string.find("グ"); // 6 
let g: String = my_string.chars().skip(g_index).take(1).collect(); 
assert_eq!("グ", g); // g is "ズ" 
相关问题