slanted W3C logo

Day 18 — Strings II

In today's lecture we look at the String accessor methods length, charAt, and one version of substring. Several examples are given.

Immutable

immutable
unchanging

String objects are immutable; once one is created its state can never be changed. This means that the text that the object encapsulates will always remain the same.

Immutable classes have many advantages for the implementer of the class. For the client, the biggest advantage is that the state of a successfully constructed object is always valid. Contrast this to the Fraction class where it is possible for the client to cause a Fraction object to have the state 0/0.

It is important to remember that it is the String object that is immutable. A non-final reference variable of type String can always be changed to refer to a different String object.

Commonly Used Accessors: length

int length()

Returns the length of this string.

      String s = "";
      String t = "T"
      String u = "UU";
      String v = " v ";
      String w = "Java";
      output.printf("%d %d %d %d %d%n",
                    s.length(),
                    t.length(),
                    u.length(),
                    v.length(),
                    w.length());

The code fragment prints 0 1 2 3 4.

Commonly Used Accessors: charAt

char charAt(int index)

Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on.

Throws IndexOutOfBoundsException if the index argument is negative or not less than the length of this string.

      String s = "Ada Lovelace";

      char c = s.charAt(0);
      output.print(c + " ");

      c = s.charAt(1);
      output.print(c + " ");

      c = s.charAt(s.length() - 1);
      output.println(c);

The code fragment prints A d e.

Statements such as:

      String s = "Ada Lovelace";

      char c = s.charAt(-1);
      c = s.charAt(s.length());
      c = s.charAt(25);

will cause an exception to be thrown.

Examples with length and charAt

Finding the index of the first 'e':

      String s = "Ada Lovelace";
      char target = 'e';
      int index = -1;
      for (int i = 0;
           i < s.length() && index < 0;
           i++)
      {
         if (s.charAt(i) == target)
         {
            index = i;
         }
      }

Counting the number of 'L' and 'l' characters:

      String s = "Ada Lovelace";
      char target = 'L';
      int count = 0;
      for (int i = 0; i < s.length(); i++)
      {
         char ci = s.charAt(i);
         if (Character.toUpperCase(ci) == target)
         {
            count++;
         }
      }

Finding the index of the last 'a':

      String s = "Ada Lovelace";
      char target = 'a';
      index = -1;
      for (int i = s.length() - 1;
           i >= 0 && index < 0;
           i--)
      {
         if (s.charAt(i) == target)
         {
            index = i;
         }
      }
      output.println(index);

Commonly Used Accessors: substring

String substring(int beginIndex)

Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

Throws IndexOutOfBoundsException if beginIndex is negative or larger than the length of this string.

      String s = "James Gosling";

      String t = s.substring(0);
      String u = s.substring(1);
      String v = s.substring(s.length() - 1);
      String w = s.substring(s.length());
      output.printf("s: %s%nt: %s%nu: %s%nv: %s%nw: %s%n",
                    s, t, u, v, w);

The code fragment prints:

s: James Gosling
t: James Gosling
u: ames Gosling
v: g
w:

Statements such as:

      String s = "James Gosling";

      c = s.substring(-1);
      c = s.substring(s.length() + 1);

will cause an exception to be thrown.

Examples with substring

An inefficient way of counting the number of 's' characters in a string:

      String s = "James Gosling";
      char target = 's';
      int count = 0;
      for ( ; s.length() > 0; )
      {
         if (s.charAt(0) == target)
         {
            count++;
         }
         s = s.substring(1);
      }

Get the last name of a person (assuming a one word first name and a one word last name):

      String s = "James Gosling";
      String lastname = "";
      boolean hasSpace = false;
      for (int i = 0;
           i < s.length() && !hasSpace;
           i++)
      {
         hasSpace = s.charAt(i) == ' ';
         if (hasSpace)
         {
            lastname = s.substring(i + 1);
         }
      }

An inefficient way to get the filename from a pathname:

      String s = "/cs/home/burton/www" + 
                 "/teaching/2009F/day18.html";
      String filename = s;
      for (int i = 0; i < s.length(); i++)
      {
         if (s.charAt(i) == '/')
         {
            filename = s.substring(i + 1);
         }
      }

To Do For Next Lecture

Continue reading Chapter 6.