欢迎访问宙启技术站
智能推送

Java 中 String 类的 toUpperCase 函数用法详解

发布时间:2023-10-29 07:01:14

String 的 toUpperCase() 方法是用来将字符串中的所有小写字母转换为大写字母的。以下是 toUpperCase() 方法的详细用法和特点。

1. 基本用法:

   String str = "hello world";
   String upperCaseStr = str.toUpperCase();
   System.out.println(upperCaseStr); // 输出: HELLO WORLD
   

toUpperCase() 方法将字符串 str 中的所有小写字母转换为大写字母,并返回转换后的新字符串。

2. 语言环境:

toUpperCase() 方法考虑了所用的语言环境,可以正确地将字符串中每个字符转换为大写字母。例如,在法语环境中,字母 "é" 将转换为 "é"。

   String str = "école";
   String upperCaseStr = str.toUpperCase();
   System.out.println(upperCaseStr); // 输出: éCOLE
   

3. 不可变性:

toUpperCase() 方法不会改变原有字符串的内容,而是返回一个新的字符串,因为 String 类是不可变类。

   String str = "hello";
   String upperCaseStr = str.toUpperCase();
   System.out.println(str); // 输出: hello
   System.out.println(upperCaseStr); // 输出: HELLO
   

4. 空串处理:

若原字符串为空串,则 toUpperCase() 方法返回空串。若原字符串仅包含非字母字符,则 toUpperCase() 方法保持原样返回。

   String str = "";
   String upperCaseStr = str.toUpperCase();
   System.out.println(upperCaseStr); // 输出: ""

   String str2 = "!@#$%^&*";
   String upperCaseStr2 = str2.toUpperCase();
   System.out.println(upperCaseStr2); // 输出: "!@#$%^&*"
   

5. 默认本地化:

若不指定语言环境,toUpperCase() 方法将根据默认的本地化环境将字符串中的小写字母转换为大写字母。

   String str = "hello world";
   String upperCaseStr = str.toUpperCase();
   System.out.println(upperCaseStr); // 输出: HELLO WORLD
   

总结:

toUpperCase() 方法是将字符串中的小写字母转换为大写字母,并返回转换后的新字符串。该方法考虑了所用的语言环境,并具有不可变性。当原字符串为空串或仅包含非字母字符时,方法会返回原字符串或保持原字符串不变。