1. Overview
1.概述
In this tutorial, we’ll cover the toUpperCase and toLowerCase methods included in the Java String class.
在本教程中,我们将介绍Java String类中的toUpperCase和toLowerCase方法。
We’ll start by creating a String called name:
我们将首先创建一个名为name的String。
String name = "John Doe";
2. Convert to Uppercase
2.转换为大写字母
To create a new uppercase String based on name, we call the toUpperCase method:
为了根据name创建一个新的大写String,我们调用toUpperCase方法。
String uppercaseName = name.toUpperCase();
This results in uppercaseName having the value “JOHN DOE”:
这导致uppercaseName具有“JOHN DOE”值。
assertEquals("JOHN DOE", uppercaseName);
Note that Strings are immutable in Java and that calling toUpperCase creates a new String. In other words, name is unchanged when calling toUpperCase.
请注意,字符串在Java中是不可变的,调用toUpperCase会创建一个新的字符串。换句话说,在调用toUpperCase时,name是没有变化的。
3. Convert to Lowercase
3.转换为小写字母
Similarly, we create a new lowercase String based on name by calling toLowerCase:
同样地,我们通过调用toLowerCase,基于name创建一个新的小写String。
String lowercaseName = name.toLowerCase();
This results in lowercaseName having the value “john doe”:
这导致lowercaseName具有“john doe”值。
assertEquals("john doe", lowercaseName);
Just as with toUpperCase, toLowerCase does not change the value of name.
与toUpperCase一样,toLowerCase并不改变name的值。
4. Change Case Using Locales
4.使用当地语言改变案例
Additionally, by supplying a Locale to the toUpperCase and toLowerCase methods, we can change the case of a String using locale-specific rules.
此外,通过向toUpperCase和toLowerCase方法提供Locale,我们可以使用本地特定的规则改变String的大小写。
For example, we can supply a Locale to uppercase a Turkish i (Unicode 0069):
例如,我们可以提供一个Locale来大写土耳其语i(Unicode 0069):。
Locale TURKISH = new Locale("tr");
System.out.println("\u0069".toUpperCase());
System.out.println("\u0069".toUpperCase(TURKISH));
Accordingly, this results in an uppercase I and a dotted uppercase I:
因此,这导致了一个大写的I和一个带点的大写I。
I
İ
We can verify this using the following assertions:
我们可以用以下断言来验证这一点。
assertEquals("\u0049", "\u0069".toUpperCase());
assertEquals("\u0130", "\u0069".toUpperCase(TURKISH));
Likewise, we can do the same for toLowerCase using the Turkish I (Unicode 0049):
同样,我们可以用土耳其语I(Unicode 0049)对toLowerCase进行同样处理。
System.out.println("\u0049".toLowerCase());
System.out.println("\u0049".toLowerCase(TURKISH));
Consequently, this results in a lowercase i and a lowercase dotless i:
因此,这导致了小写的i和小写的无点i。
i
ı
We can verify this using the following assertions:
我们可以用以下断言来验证这一点。
assertEquals("\u0069", "\u0049".toLowerCase());
assertEquals("\u0131", "\u0049".toLowerCase(TURKISH));
5. Conclusion
5.总结
In conclusion, the Java String class includes the toUpperCase and toLowerCase methods for changing the case of a String. If needed, a Locale can be supplied to provide locale-specific rules when changing the case of a String.
总之,Java String 类包括toUpperCase和toLowerCase方法,用于改变String的大小写。如果需要,可以提供一个Locale,以便在改变String的大小写时提供针对当地的规则。
The source code for this article, including examples, can be found over on GitHub.
这篇文章的源代码,包括例子,可以在GitHub上找到over。