CS 051 Fall 2011

Lecture 31

String Methods

We looked at several methods of the String class today:

Class example StringsDemo demonstrates how each of these works.

String Practice

We wrote a method that took in a String of text, and a String word, and counted how many times
the word appeared in the text.

public int wordCount(String text, String word)
{
   int count = 0;
   int pos = text.indexOf(word);

   while (pos >= 0)
   {
     count++;
     pos = text.indexOf(word, pos + word.length());
   }

   return count;
}

This simple version would not catch words that were the same, but were capitalized. So, we
modified our method with the toLowerCase method call to catch all occurrences of the word.

public int wordCount(String text, String word)
{
   int count = 0;

   text = text.toLowerCase();
   word = word.toLowerCase();

   int pos = text.indexOf(word);

   while (pos >= 0)
   {
     count++;
     pos = text.indexOf(word, pos + word.length());
   }

   return count;
}

We looked at class example BuildDemoPage, which takes a class name and applet
sizes to generate the html code necessary to put a java applet in a web page.

This program had several interesting features. It uses the \n character to
create a newline in the string. It also uses the sequence \" to insert a printable
double quote inside of our string.

Finally, we looked at the FindLinks program, which takes the source code of a web page
and identifies all of the hyperlinks in page.