问题:
I'd like to capitalize the first letter of a &str
.我想将&str
的第一个字母大写。 It's a simple problem and I hope for a simple solution.这是一个简单的问题,我希望有一个简单的解决方案。 Intuition tells me to do something like this:直觉告诉我做这样的事情:
let mut s = "foobar";
s[0] = s[0].to_uppercase();
But &str
s can't be indexed like this.但是&str
不能像这样被索引。 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.我将&str
转换为迭代器,将迭代器转换为向量,将向量中的第一项大写,这将创建一个迭代器,我对其进行索引,创建一个Option
,我将其解开以提供大写的第一个字母. Then I convert the vector into an iterator, which I convert into a String
, which I convert to a &str
.然后我将向量转换为迭代器,将其转换为String
,然后将其转换为&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;
Is there an easier way than this, and if so, what?有没有比这更简单的方法,如果有,那又怎样? If not, why is Rust designed this way?如果不是,为什么 Rust 是这样设计的?