我想将 "foo.bar.baz"
转换为 "FooBarBaz"
。我的输入永远只是 ASCII。我试过:
let result = "foo.bar.baz"
.to_string()
.split(".")
.map(|x| x[0..1].to_string().to_uppercase() + &x[1..])
.fold("".to_string(), |acc, x| acc + &x);
println!("{}", result);
但这感觉效率很低。
最佳答案
您的解决方案是一个好的开始。您可能可以在没有“功能”风格的堆分配的情况下使其工作;不过,我更喜欢将复杂的逻辑放入普通的 for
循环中。
另外,我不喜欢在没有实际检查的情况下假设输入是 ASCII - 这应该适用于任何字符串。
您可能还可以在代码中使用 String::with_capacity
以避免在标准情况下重新分配。
fn dotted_to_pascal_case(s: &str) -> String {
let mut result = String::with_capacity(s.len());
for part in s.split('.') {
let mut cs = part.chars();
if let Some(c) = cs.next() {
result.extend(c.to_uppercase());
}
result.push_str(cs.as_str());
}
result
}
fn main() {
println!("{}", dotted_to_pascal_case("foo.bar.baz"));
}
关于string - 如何将反向域表示法转换为 PascalCase?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48341384/