CS51 - Fall 2009 - Lecture 30

  • Exercise 16.5.2:
       - String s = "I drank java on the island of Java."
       - s.indexOf("java");
       - s.indexOf("java", 8);
       - s.indexOf("java", 9);
       - s.indexOf("an");
       - s.indexOf("an", 4);
       - s.indexOf("an", 5);

  • % method

  • A quick note on equality
       - java String pool
       - "a string" == "a string"
          true
       - always use .equals for Strings!

  • show StringDemos demo

  • show BuildDemoPage demo
       
  • look at BuildDemoPage code
       - '+' for concatenate
       - \n
       - \"
       - other special characters (http://java.sun.com/docs/books/tutorial/java/data/characters.html)
          - \t
          - \\
          - \'
       - why do we need these escape characters?
       - html tags
          - <tag>...</tag>
          - a few special tags that are by themselves: <p>, <br>
          - view page source
       - something to watch out for
          - with any code with user input, be careful about malicious users or corner cases
          - what if the class name has an html tag in it?

  • counting occurrences of a word in a string
       - public int wordCount(String text, String word){
          int count = 0;
          int index = text.indexOf(word, 0);

          while ( index >= 0 ){
             index = text.indexOf(word, index + 1);
             count++;
          }
        return count;
       }
       
       - what if we wanted non-overlapping occurrences?
          - index = text.indexOf(word, index + word.length());

  • http://www.sr.se/P1/src/sing/#