最佳答案
我想把 &str
的第一个字母大写。这是一个简单的问题,我希望有一个简单的解决方案。直觉告诉我要这样做:
let mut s = "foobar";
s[0] = s[0].to_uppercase();
But &str
s can't be indexed like this. The only way I've been able to do it seems overly convoluted. I convert the &str
to an iterator, convert the iterator to a vector, upper case the first item in the vector, which creates an iterator, which I index into, creating an Option
, which I unwrap to give me the upper-cased first letter. Then I convert the vector into an iterator, which I convert into a String
, which I convert to a &str
.
let s1 = "foobar";
let mut v: Vec<char> = s1.chars().collect();
v[0] = v[0].to_uppercase().nth(0).unwrap();
let s2: String = v.into_iter().collect();
let s3 = &s2;
还有比这更简单的方法吗? 如果有,那又是什么? 如果没有,为什么 Rust 被设计成这样?