Recipe 3.9 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 is covered in Chapter 15. While the equals( ) method tells you if another string is exactly the same, equalsIgnoreCase( ) 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 false");

If you run this, it prints the first name changed to uppercase and lowercase, then it reports that both methods work as expected.

C:\javasrc\strings>java  Case Normal: Java Cookbook Upper:  JAVA COOKBOOK Lower:  java cookbook equals( ) correctly reports false equalsIgnoreCase( ) correctly reports true

See Also

Regular expressions make it simpler to ignore case in string searching (see Chapter 4).



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net