将 Java 字符串转换为大写
可以使用toUpperCase()方法将Java字符串转换为大写。
将Java字符串转换为大写
![java string to uppercase](https://cdn.silicloud.com/blog-img/blog/img/65647bd0a4b2f92e6c72c558/2-0.png)
- Java String toUpperCase() method has two variants – toUpperCase() and toUpperCase(Locale locale).
- Conversion of the characters to upper case is done by using the rules of default locale. Calling toUpperCase() function is same as calling toUpperCase(Locale.getDefault()).
- Java String to upper case method is locale sensitive, so use it carefully with strings that are intended to be used locale independent. For example programming language identifiers, HTML tags, protocol keys etc. Otherwise you might get unwanted results.
- To get correct upper case results for locale insensitive strings, use toUpperCase(Locale.ROOT) method.
- String toUpperCase() returns a new string, so you will have to assign that to another string. The original string remains unchanged because String is immutable.
- If locale is passed as null to toUpperCase(Locale locale) method, then it will throw NullPointerException.
Java字符串转换为大写的示例
让我们看一个简单的例子,将一个字符串转换为大写并打印出来。
String str = "Hello World!";
System.out.println(str.toUpperCase()); //prints "HELLO WORLD!"
我们还可以使用Scanner类来获取用户输入,然后将其转换为大写并打印出来。以下是一个完整的示例程序,用于将Java字符串转换为大写并打印出来。
package com.Olivia.string;
import java.util.Scanner;
public class JavaStringToUpperCase {
public static void main(String[] args) {
String str = "hello World!";
String strUpperCase = str.toUpperCase();
System.out.println("Java String to Upper Case: " + strUpperCase);
readUserInputAndPrintInUpperCase();
}
private static void readUserInputAndPrintInUpperCase() {
Scanner sc = new Scanner(System.in);
System.out.println("Please write input String and press Enter:");
String str = sc.nextLine();
System.out.println("Input String in Upper Case = " + str.toUpperCase());
sc.close();
}
}
以下控制台输出显示了上述程序的样例执行。
Java String to Upper Case: HELLO WORLD!
Please write input String and press Enter:
Welcome to JournalDev Tutorials
Input String in Upper Case = WELCOME TO JOURNALDEV TUTORIALS
这就是Java字符串转大写的示例。参考:API文档。