CS51 - Fall 2009 - Lecture 29

  • Quiz: problem 15.4.4

  • Strings
       - Where have we seen them so far?
          - "This is a string"
          - ""
          - Label label;
             - label.getText();
          - String[] words;
          - System.out.println(String);
       - What methods might we want?
          - concatenation: +
          - substring
          - indexOf
          - startsWith
          - endsWith
          - trim
          - split
          - equals
          - compareTo
          - length
          - replace
          - lowercase
          - uppercase
       - Strings are a class and are therefore objects
       - Strings are immutable!
       - How do you think they're implemented?
          - Array of characters... more on characters later

  • Some examples
       - String test = " This is a string";
       - test.substring(0, 2);
          " T"
       - test.substring(5, 14);
          " is a str"
       - test.substring(9);
          "a string"
       - test.startsWith(" Thi");
          true
       - test.startsWith(" this");
          false
       - test.endsWith("a");
          false
       - test.endsWith("string");
          true
       - test.toLowercase();
          " this is a string";
       - test.toUppercase();
          " THIS IS A STRING";
       - test.trim();
          "This is a string"
       - test.indexOf("i");
          3
       - test.indexOf("is");
          3
       - test.indexOf("is a string");
          3
       - test.indexOf("banana");
          -1
       - test.indexOf("i", 4);
          6
       - test.replace("s", "S");
          " ThiS iS a String"
       - test.replace("is", "si");
          " Thsi si a string"
       - test.split(" ");
          ["", "This", "is", "a", "string"];
       - test.trim().toUppercase().substring(0, 4);
          "THIS";
       - test.toLowercase().trim().substring(5, 7).startsWith(" i");
          true
       - test.subString(test.indexOf("i"), test.indexOf("i", test.indexOf("i")+1));
          "is "
       - test.subString(0,10) + "longer " + test.subString(11);
          "This is a longer string"
       - test.length();
          17
       - test.toCharArray()
          [' ', 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g']
       - test == " This is a string";
          false
       - test.equals(" This is a string");
          true
       - test.equals(" this is a string");
          false
       - test.equalsIgnoreCase(" this is a string");
          true

  • nibbler lab
       - due Tuesday night (24 hour extension)
       - work alone
       - two parts
          - Part I - just implementing the snake
          - Part II - nibble field
          - only need a design for part I
          - only submit part II (which will also contain your work from part I)