Controlling Case

Problem

You need to convert strings to upper case or lowercase, or to compare strings without regard for case.

Solution

The String class has a number of methods for dealing with documents in a particular case. toUpperCase( ) and toLowerCase( ) each return a new string that is a copy of the current string, but converted as the name implies. Each can be called either with no arguments or with a Locale argument specifying the conversion rules; this is necessary because of internationalization. Java provides significantly more internationalization and localization features than ordinary languages, a feature that will be covered in Chapter 14. While the equals( ) method tells you if another string is exactly the same, there is also equalsIgnoreCase( ), which tells you if all characters are the same regardless of case. Here, you can’t specify an alternate locale; the system’s default locale is used.

// Case.java String name = "Java Cookbook"; System.out.println("Normal:\t" + name); System.out.println("Upper:\t" + name.toUpperCase( )); System.out.println("Lower:\t" + name.toLowerCase( )); String javaName = "java cookBook"; // As if it were Java identifiers :-) if (!name.equals(javaName)) System.err.println("equals( ) correctly reports false"); else System.err.println("equals( ) incorrectly reports true"); if (name.equalsIgnoreCase(javaName)) System.err.println("equalsIgnoreCase( ) correctly reports true"); else System.err.println("equalsIgnoreCase( ) incorrectly reports ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.