如何将 toUpperCase() 应用于 Java 中的空字符串?
How is possible to apply toUpperCase() on an empty String in Java?
我想如果我 运行 这个
System.out.println("toUpperCase() on empty String:"+ "".toUpperCase());
它returns 是一个空字符串。这怎么可能? toUpperCase() 在这种情况下应该会失败,不是吗?谢谢!
为什么会失败?它将输入字符串的任何字符转换为大写。在您的示例中,"any character" 相当于 0 个字符。
Javadoc 没有说空字符串应该失败,这
意味着它不应该失败:
Converts all of the characters in this String to upper case using the
rules of the default locale. This method is equivalent to
toUpperCase(Locale.getDefault()).
Note: This method is locale sensitive, and may produce unexpected
results if used for strings that are intended to be interpreted locale
independently. Examples are programming language identifiers, protocol
keys, and HTML tags. For instance, "title".toUpperCase() in a Turkish
locale returns "T\u0130TLE", where '\u0130' is the LATIN CAPITAL
LETTER I WITH DOT ABOVE character. To obtain correct results for
locale insensitive strings, use toUpperCase(Locale.ENGLISH).
Returns: the String, converted to uppercase.
空字符串不为 null,因此,您可以在其上调用所有 String 方法。
我想如果我 运行 这个
System.out.println("toUpperCase() on empty String:"+ "".toUpperCase());
它returns 是一个空字符串。这怎么可能? toUpperCase() 在这种情况下应该会失败,不是吗?谢谢!
为什么会失败?它将输入字符串的任何字符转换为大写。在您的示例中,"any character" 相当于 0 个字符。
Javadoc 没有说空字符串应该失败,这 意味着它不应该失败:
Converts all of the characters in this String to upper case using the rules of the default locale. This method is equivalent to toUpperCase(Locale.getDefault()).
Note: This method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently. Examples are programming language identifiers, protocol keys, and HTML tags. For instance, "title".toUpperCase() in a Turkish locale returns "T\u0130TLE", where '\u0130' is the LATIN CAPITAL LETTER I WITH DOT ABOVE character. To obtain correct results for locale insensitive strings, use toUpperCase(Locale.ENGLISH).
Returns: the String, converted to uppercase.
空字符串不为 null,因此,您可以在其上调用所有 String 方法。