如何大写Rust中字符串中的所有字符?

5 rust

这里有一个答案,说明如何将字符串中的ASCII字符大写.这对我的具体问题来说还不够.

sso*_*low 7

对于那些在Google上徘徊的人来说,自Rust 0.13.0以来,情况有所改善.(我在Rust 1.13.0上)

&str(字符串切片)提供to_uppercase(),你可以强制任何东西.

// First, with an &str, which any string can coerce to.
let str = "hello øåÅßç";
let up = str.to_uppercase();
println!("{}", up);

// And again with a String
let nonstatic_string = String::from(str);
let up2 = nonstatic_string.to_uppercase();
println!("{}", up2);
// ...if this fails in an edge case, use &nonstatic_string to force coercion
Run Code Online (Sandbox Code Playgroud)

关于Matthieu M.的评论,这种转换应该完全符合Unicode标准.

这是Rust Playground上的一个可运行的副本

如果它有助于新手了解正在发生的事情:

  1. String实现Deref<Target=str>,所以你可以调用任何str方法String.
  2. str::to_uppercase()take &str(一个借来的,不可变的切片.换句话说,是对字符串的只读引用),所以它几乎可以接受任何东西.
  3. str::to_uppercase()分配一个new String并返回它,因此它的返回值不受输入的借用规则的约束.

在年底的评论中提及需要注意的是,如果你打电话my_string.to_uppercase()str::to_uppercase(my_string),然后它会抱怨这样的:

expected &str, found struct `std::string::String`
Run Code Online (Sandbox Code Playgroud)

发生的事情my_string.to_uppercase()实际上并不等同......它相当于str::to_uppercase(&my_string).

(如果您没有使用引用,则不能自动deref.&在进行方法调用时不需要提供方法调用,因为&self方法定义中为您执行此操作.)


Dog*_*ert 4

我认为没有任何函数可以直接执行此操作,但是您可以使用特征中的函数UnicodeCharchars例如map

\n\n
let str = "hello \xc3\xb8\xc3\xa5\xc3\x85\xc3\x9f\xc3\xa7";\nlet up = str.chars().map(|c| c.to_uppercase()).collect::<String>();\nprintln!("{}", up);\n
Run Code Online (Sandbox Code Playgroud)\n\n

输出:

\n\n
HELLO \xc3\x98\xc3\x85\xc3\x85\xc3\x9f\xc3\x87\n
Run Code Online (Sandbox Code Playgroud)\n\n

测试于rustc 0.13.0-dev (66601647c 2014-11-27 06:41:17 +0000)

\n