杰瑞科技汇

Java String大小写转换如何实现?

Of course! In Java, handling the case (uppercase/lowercase) of a String is a very common task. The primary tool for this is the String class itself, which provides several built-in methods.

Here's a comprehensive guide to Java string case operations, covering the basics, edge cases, and best practices.

Converting to Uppercase

To convert all characters in a string to uppercase, you use the toUpperCase() method.

Method Signature:

public String toUpperCase()

Example:

String original = "Hello World! Java 123.";
String upperCase = original.toUpperCase();
System.out.println(Original:  + original);
System.out.println(Uppercase: + upperCase);

Output:

Original: Hello World! Java 123.
Uppercase: HELLO WORLD! JAVA 123.

Key Points:

  • It returns a new String object; the original string is not modified (since String objects are immutable).
  • It handles numbers and special characters by leaving them unchanged.
  • The conversion is based on the rules of the English language by default.

Converting to Lowercase

To convert all characters in a string to lowercase, you use the toLowerCase() method.

Method Signature:

public String toLowerCase()

Example:

String original = "Hello World! Java 123.";
String lowerCase = original.toLowerCase();
System.out.println(Original:  + original);
System.out.println(Lowercase: + lowerCase);

Output:

Original: Hello World! Java 123.
Lowercase: hello world! java 123.

Key Points:

  • Like toUpperCase(), it returns a new String object and leaves the original unchanged.
  • It also leaves numbers and special characters unchanged.

Case-Insensitive Comparison

A very frequent requirement is to compare two strings without considering their case. Java provides two main ways to do this.

a) equalsIgnoreCase()

This is the most straightforward method. It compares two strings lexicographically, ignoring case differences.

Method Signature:

public boolean equalsIgnoreCase(String anotherString)

Example:

String str1 = "Java";
String str2 = "java";
String str3 = "JAVA";
String str4 = "Python";
System.out.println(str1.equals(str2));       // false (case-sensitive)
System.out.println(str1.equalsIgnoreCase(str2)); // true (case-insensitive)
System.out.println(str1.equalsIgnoreCase(str3)); // true
System.out.println(str1.equalsIgnoreCase(str4)); // false

Output:

false
true
true
false

b) compareToIgnoreCase()

This method is similar to compareTo(), but it ignores case. It returns:

  • 0 if the strings are equal (ignoring case).
  • A negative value if the calling string is lexicographically less than the argument string.
  • A positive value if the calling string is lexicographically greater than the argument string.

Method Signature:

public int compareToIgnoreCase(String str)

Example:

String str1 = "apple";
String str2 = "Banana";
String str3 = "Apple";
// 'a' (97) vs 'B' (66) -> 'a' is greater, so result is positive
System.out.println(str1.compareToIgnoreCase(str2)); 
// 'a' vs 'A' -> they are equal, so result is 0
System.out.println(str1.compareToIgnoreCase(str3)); 
// 'B' vs 'a' -> 'B' is less, so result is negative
System.out.println(str2.compareToIgnoreCase(str1)); 

Output:

-1
0
1

(Note: The exact negative/positive value can depend on the character set, but the sign will always be correct for comparison).


Advanced Case Conversion (with Locale)

For simple English, toUpperCase() and toLowerCase() work perfectly. However, for international applications, you should consider language-specific rules. For example, in Turkish, the uppercase of 'i' is , and the lowercase of 'I' is .

The String class provides overloaded versions of these methods that accept a Locale object.

Method Signatures:

public String toUpperCase(Locale locale)
public String toLowerCase(Locale locale)

Example (Turkish Locale):

// The string contains the character 'i'
String str = "i";
// Default (English) locale
System.out.println("Default Upper: " + str.toUpperCase()); // -> I
// Turkish locale
System.out.println("Turkish Upper:  " + str.toUpperCase(new Locale("tr", "TR"))); // -> İ

Output:

Default Upper: I
Turkish Upper:  İ

Best Practice: If your application is intended for a global audience, always use the locale-aware versions. For most internal or US-centric applications, the default versions are sufficient.


Practical Use Cases

a) Case-Insensitive Search

String text = "The quick brown fox jumps over the lazy dog.";
String searchTerm = "FOX";
// This would fail
if (text.contains(searchTerm)) {
    System.out.println("Found (case-sensitive)!");
} else {
    System.out.println("Not found (case-sensitive)."); // This will be printed
}
// This works
if (text.toLowerCase().contains(searchTerm.toLowerCase())) {
    System.out.println("Found (case-insensitive)!"); // This will be printed
}

b) Normalizing User Input

When getting input from a user (e.g., for a username or a command), it's common to convert it to a standard case.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter your username: ");
String userInput = scanner.nextLine();
// Store username in lowercase for consistency
String normalizedUsername = userInput.toLowerCase();
System.out.println("Your username has been set to: " + normalizedUsername);

c) Checking for a Specific Prefix/Suffix (Case-Insensitive)

String filename = "REPORT.TXT";
if (filename.toLowerCase().startsWith("report.")) {
    System.out.println("This is a report file.");
}

Summary Table

Method Description Returns Example
toUpperCase() Converts all characters to uppercase. String "Java".toUpperCase() -> "JAVA"
toLowerCase() Converts all characters to lowercase. String "Java".toLowerCase() -> "java"
equalsIgnoreCase() Compares two strings, ignoring case. boolean "Java".equalsIgnoreCase("java") -> true
compareToIgnoreCase() Compares two strings lexicographically, ignoring case. int "apple".compareToIgnoreCase("Banana") -> -1
toUpperCase(Locale) Converts to uppercase using a specific locale's rules. String "i".toUpperCase(new Locale("tr")) ->
toLowerCase(Locale) Converts to lowercase using a specific locale's rules. String "I".toLowerCase(new Locale("tr")) ->
分享:
扫描分享到社交APP
上一篇
下一篇