slanted W3C logo

Day 20 — Strings IV

In today's lecture we look at the comparator methods equals, equalsIgnoreCase and compareTo, and the transformer methods trim, toUpperCase, toLowerCase, and replace.

Comparators: equals

equals returns true if two string instances have the same state (represent the same sequence of text), and false otherwise.

      String s = "ABC";
      String t = s;
      String u = "abc";
      
      output.println("s same as t: " + s.equals(t));
      output.println("s same as u: " + s.equals(u));

The code fragment prints:

s same as t: true
s same as u: false

Comparators: equalsIgnoreCase

If you want to check if two strings represent the same text and you do not care about the case of strings, use equalsIgnoreCase:

      String s = "ABC";
      String t = s;
      String u = "abc";
      
      output.println("s same as t ignoring case: " +
                     s.equalsIgnoreCase(t));
      output.println("s same as u ignoring case: " +
                     s.equalsIgnoreCase(u));

The code fragment prints:

s same as t: true
s same as u: true

Comparators: compareTo

compareTo will compare two strings by lexicographical (dictionary) order. Suppose you have two string variables named s and t:

s.compareTo(t) returns less than zero if the String s precedes the String t
s.compareTo(t) returns zero if s.equals(t) is true
s.compareTo(t) returns greater than zero if the String s follows the String t

The actual value returned by compareTo has a specific meaning; see the API if you are curious.

Example Using compareTo

Based on last year's midterm labtest: Repeatedly read in a person's full name (first name followed by middle names followed by family name all separated by spaces); if the family name starts with a letter from A-M output "A-M", otherwise output "N-Z".

      final String SPLIT_AT = "N";
      
      for (; input.hasNext(); )
      {
         String name = input.nextLine();
         int index = name.lastIndexOf(' ');
         String last = name.substring(index + 1);
         if (last.compareTo(SPLIT_AT) < 0)
         {
            output.println("A-M");
         }
         else
         {
            output.println("N-Z");
         }
      }

More Comparators

The String class has a large API with several other comparator methods. See the API for these other methods:

int     compareToIgnoreCase(String str)
boolean endsWith(String suffix)
int     lastIndexOf(int ch)
int     lastIndexOf(int ch, int fromIndex)
int     lastIndexOf(String str)
int     lastIndexOf(String str, int fromIndex)
boolean startsWith(String prefix)

Transformers

A transformer method returns a reference to a new string that is computed by transforming the characters of an existing string.

Transformer: trim

String trim()

Returns a copy of the string, with leading and trailing whitespace omitted.

      String s = "   hello   ";
      String t = "hello   ";
      String u = "hello";
      
      String v = s.trim();
      String w = t.trim();
      String x = u.trim();
      
      output.println(":" + s + ":" + " *" + v + "*");
      output.println(":" + t + ":" + " *" + w + "*");
      output.println(":" + u + ":" + " *" + x + "*");

The above code fragment prints:

:   hello   :
*hello*

:hello   :
*hello*

:hello:
*hello*

Transformers: toUpperCase and toLowerCase

The methods toUpperCase and toLowerCase each return a copy of an existing string with the characters converted to upper and lower case.

      String s = "aBcDeFgHiJ";
      
      String upper = s.toUpperCase();
      String lower = s.toLowerCase();
      
      output.println(s);
      output.println(upper);
      output.println(lower);

The above code fragment prints:

aBcDeFgHiJ
ABCDEFGHIJ
abcdefghij

Transformers: replace

String replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

      String s = "sparring with a purple porpoise";
      
      String t = s.replace('p', 't');
      String u = s.replace('x', 'y');

The above code fragment prints:

starring with a turtle tortoise
sparring with a purple porpoise

Transformers: replace

String
replace(CharSequence target, CharSequence replacement)


Returns a new string resulting from replacing all occurrences of the substring target in this string with replacement. The replacement proceeds from the beginning of the string to the end. Throws NullPointerException if target or replacement is null.

      String s = "hiho, hiho, it's off to work we go";
      
      String t = s.replace("hiho", "ohno");
      output.println(s);
      output.println(t);

The above code fragment prints:

hiho, hiho, it's off to work we go
ohno, ohno, it's off to work we go

Transformers: replace

It is important to remember that the replacement proceeds from the beginning of the string to the end.

      String s = "aaaaaa";
      
      String t = s.replace("aa", "b");
      output.println(s);
      output.println(t);

The above code fragment prints:

aaaaaa
bbb

Converting Strings to Numbers

Often you will want to convert a string to a number. The String class does not provide methods for doing such conversions.

A wrapper class allows the client to create an object the corresponds to a primitive value. There are 8 wrapper classes, one for each primitive type.

Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

Converting Strings to Numbers

Converting a string to a number can be accomplished using the appropriate static method in each wrapper class:

      String ival = "1";
      String lval = "5000000000";
      String val = "3.5";
      
      int anInt = Integer.parseInt(ival);
      long aLong = Long.parseLong(lval);
      float aFloat = Float.parseFloat(val);
      double aDouble = Double.parseDouble(val);

To Do For Next Lecture

Continue reading Chapter 6 (especially Section 6.4).