在Rust中把字符串转换成大写或小写字母的多种方法介绍

1,944 阅读1分钟

本程序通过实例向你展示了在Rust中把字符串转换成大写字母的多种方法。

例如,如果给定的字符串是Hello,输出为大写的HELLO。如果给定的字符串是Hello,输出为小写的Hello。

如何在Rust中把小写字符串转换成大写?

在这里,让我们看看如何在Rust中把字符串转换为大写字母。

有多种方法可以将字符串转换为大写字母。

  • use str::to_uppercase function to_uppercase 函数返回字符串的大写字母

下面是一个示例程序

fn main() {
    let str = "Hello World";
    println!(" {}", str.to_uppercase());
}

输出

 HELLO WORLD
  • use str::to_ascii_uppercase function to_ascii_uppercase 函数返回一个字符串中ASCII字符的大写字母。

ASCII字符,如a to z ,被转换为A to Z 。非ASCII字符不被改变,返回相同的内容。

下面是一个示例程序

fn main() {
    let str = "Hello World";
    println!(" {}", str.to_ascii_uppercase());
}

输出:

 HELLO WORLD

如何在Rust中把字符串转换为小写字母

在这里,让我们看看如何在Rust中把字符串转换为小写字母。 字符串中的每个大写字母都被转换为小写。

  • use str::to_ascii_lowercase function to_ascii_lowercase 函数返回一个字符串中ASCII字符的小写字母。

ASCII字符,如A to Z ,被转换为a to z 。非ASCII字符不被改变,返回相同的内容。

下面是一个示例程序

fn main() {
    let str = "Hello World";
    println!(" {}", str.to_ascii_lowercase());
}

输出

hello world
  • use str::to_lowercase function to_lowercase 函数返回一个字符串的小写字母。

下面是一个程序的例子

fn main() {
    let str = "HELLO WORLD";
    println!(" {}", str.to_lowercase());
}

输出:

hello world

结论

在这篇文章中,通过实例学习了多种方法,包括

  • 如何将字符串转换为大写的字符串?
  • 如何将字符串转换为小写字符串?