Lecture 16: Objects: String FileLecture 16: Objects: …eugene/cs170/lectures/lecture16...Lecture...
Transcript of Lecture 16: Objects: String FileLecture 16: Objects: …eugene/cs170/lectures/lecture16...Lecture...
Lecture 16: Objects: String FileLecture 16: Objects: String, File
CS 170, Section 000
27 October 200927 October 2009
10/27/2009 CS170, Section 000, Fall 2009 1
Lecture Plan
More on the String classGentle introduction to objects
Chapter 8 (cont’d): File Class (another object)Files directories browsingFiles, directories browsing
Text input/output
Homework 5: Breaking the Caesar cipherDue Wednesday, Nov 4th (new date)
CS170, Section 000, Fall 2009 2
The String Class: Ch 8.1-8.4
• Constructing a String Object
String message2 = new String("Welcome to Java“);String s1 = new String();
• Since strings are used frequently JavaSince strings are used frequently, Java provides a shorthand initializer for creating a string:string:
String message1 = "Welcome to Java“; String s2 “”
3
String s2 = “”;
Strings Are Immutable
• A String object is immutable; its contents cannot be changedcannot be changed
• Does the following code change the contents f h ?of the string?
String s = "Java";s = "HTML";
4
Trace Code
String s = "Java";s = "HTML";
After executing String s = "Java"; After executing s = "HTML";
: String
String object for "Java"
s : String
String object for "Java"
This string object is now unreferenced
s
: String
String object for "HTML"
Contents cannot be changed
5
Trace Code
String s = "Java";"HTML"s = "HTML";
After executing String s = "Java"; After executing s = "HTML";
: String
String object for "Java"
s : String
String object for "Java"
This string object is now unreferenced
s
: String
String object for "HTML"
Contents cannot be changed
6
String Comparisons java.lang.String
+equals(s1: String): boolean R t t if thi t i i l t t i 1+equals(s1: String): boolean +equalsIgnoreCase(s1: String):
boolean +compareTo(s1: String): int
Returns true if this string is equal to string s1.Returns true if this string is equal to string s1 case-
insensitive. Returns an integer greater than 0, equal to 0, or less than 0p ( g)
+compareToIgnoreCase(s1: String): int
Returns an integer greater than 0, equal to 0, or less than 0to indicate whether this string is greater than, equal to, or less than s1.
Same as compareTo except that the comparison is case-insensitiveint
+regionMatches(toffset: int, s1: String, offset: int, len: int): boolean
+regionMatches(ignoreCase: boolean,
insensitive.Returns true if the specified subregion of this string exactly
matches the specified subregion in string s1. Same as the preceding method except that you can specify
toffset: int, s1: String, offset: int, len: int): boolean
+startsWith(prefix: String): boolean +endsWith(suffix: String): boolean
p g p y p ywhether the match is case-sensitive.
Returns true if this string starts with the specified prefix. R t t if thi t i d ith th ifi d ffi
7
+endsWith(suffix: String): boolean Returns true if this string ends with the specified suffix.
String Comparisons
equals
String s1 = new String("Welcome“);
String s2 = new String(“welcome”);String s2 new String( welcome );
if (s1.equals(s2)){
// s1 and s2 have the same contents
}
if (s1 == s2) {// s1 and s2 have the same reference
8}
// s1 and s2 have the same reference
String Length, Characters, and Combining Strings
java.lang.String
+l th() i t R t th b f h t i thi t i+length(): int +charAt(index: int): char +concat(s1: String): String
Returns the number of characters in this string.Returns the character at the specified index from this string. Returns a new string that concatenate this string with string s1.
9
Finding String Length
Fi di t i l th i th l th()Finding string length using the length()method:
message = "Welcome";
message length()message.length()
10
Retrieving Individual Characters in a String
• Use message.charAt(index)
• Index starts from 0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14Indices
W e l c o m e t o J a v a
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
message
Indices
message.charAt(0) message.charAt(14)message.length() is 15
Do not use message[0] !!!
11
String Concatenation
String s3 = s1.concat(s2);
String s3 = s1 + s2;
s1 + s2 + s3 + s4 + s5
(((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5);
12
Extracting Substrings
java.lang.String
+subString(beginIndex: int): Returns this string’s substring that begins with the character at the subString(beginIndex: int): String
+subString(beginIndex: int, endIndex: int): String
g g gspecified beginIndex and extends to the end of the string, as shown in Figure 8.6.
Returns this string’s substring that begins at the specified beginIndex and extends to the character at index endIndex – 1 asendIndex: int): String
beginIndex and extends to the character at index endIndex 1, as shown in Figure 8.6. Note that the character at endIndex is not part of the substring.
13
Extracting Substrings
• Using the substring method in the String class
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14Indices
String s1 = "Welcome to Java";
W e l c o m e t o J a v a
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
message
Indices
message.substring(0, 11) message.substring(11)
String s2 = s1.substring(0, 11) + "HTML";
14
Examples
"Welcome" toLowerCase() “welcome”Welcome .toLowerCase()
"Welcome".toUpperCase()
welcome
“WELCOME”
"Welcome".replace('e', 'A’) “WAlcomA”
15
Splitting a String
String str = “Cat-Dog-Mouse”;
String[] tokens = str.split(“-”);
System.out.println(tokens[2]);
System.out.println(“eats”);
System out println(tokens[0])System.out.println(tokens[0]);
{“Cat”, “Dog”, “Mouse”}
16
Finding a Character or a Substring in a String
java.lang.String
+indexOf(ch: char): int
+indexOf(ch: char, fromIndex: int): int
Returns the index of the first occurrence of ch in the string. Returns -1 if not matched.
Returns the index of the first occurrence of ch after fromIndex in the string Returns 1 if not matchedint): int
+indexOf(s: String): int
+indexOf(s: String, fromIndex: int): int
the string. Returns -1 if not matched.Returns the index of the first occurrence of string s in this string.
Returns -1 if not matched. Returns the index of the first occurrence of string s in this string
ft f I d R t 1 if t t h dint): int +lastIndexOf(ch: int): int +lastIndexOf(ch: int,
f I d i ) i
after fromIndex. Returns -1 if not matched.Returns the index of the last occurrence of ch in the string.
Returns -1 if not matched. Returns the index of the last occurrence of ch before fromIndex
fromIndex: int): int +lastIndexOf(s: String): int +lastIndexOf(s: String,
in this string. Returns -1 if not matched.Returns the index of the last occurrence of string s. Returns -1 if
not matched. Returns the index of the last occurrence of string s before
17
fromIndex: int): int g
fromIndex. Returns -1 if not matched.
Finding a Character or a Substring in a String
i"Welcome to Java".indexOf('W') returns 0.
"Welcome to Java".indexOf('x') returns -1.
"W l J " i d Of(' ' 5) t 9"Welcome to Java".indexOf('o', 5) returns 9.
"Welcome to Java".indexOf("come") returns 3.
"W l t J " i d Of("J " 5) t 11"Welcome to Java".indexOf("Java", 5) returns 11.
"Welcome to Java".indexOf("java", 5) returns -1.
"Welcome to Java" lastIndexOf('a') returns 14"Welcome to Java".lastIndexOf('a') returns 14.
18
Example: Pig Latin
• Ancay uoyay eakspay igpay atinlay?
If h d b i i h h i l i• If the word begins with a consonant such as string or latin– divide the word at the first vowel, swap the front and back halves, and append "ay" to the end
• ing + str + ay gives ingstray and atin + l + ay gives atinlay.
If th d b i ith l h I• If the word begins with a vowel--such as am or I– just append "yay" to the word
– am + yay gives amyay and i + yay gives iyay.
• If the word has no vowels (not counting 'y')--such as my or hymn– just append "yay" to it
• my + yay gives myyay and hymn + yay gives hymnyay• my + yay gives myyay and hymn + yay gives hymnyay.
• Implementation: /home/cs170000/inclass/oct27/PigLatin.java
10/28/2009 CS170, Section 000, Fall 2009 19
Converting, Replacing, and Splitting Strings
java.lang.String
+toLowerCase(): String +toUpperCase(): String
Returns a new string with all characters converted to lowercase. Returns a new string with all characters converted to uppercase+toUpperCase(): String
+trim(): String +replace(oldChar: char,
newChar: char): String
Returns a new string with all characters converted to uppercase.Returns a new string with blank characters trimmed on both sides. Returns a new string that replaces all matching character in this
string with the new character. +replaceFirst(oldString: String,
newString: String): String +replaceAll(oldString: String,
newString: String): String
Returns a new string that replaces the first matching substring in this string with the new substring.
Returns a new string that replace all matching substrings in this string with the new substringnewString: String): String
+split(delimiter: String): String[]
string with the new substring. Returns an array of strings consisting of the substrings split by the
delimiter.
20
Review questions
• Suppose s is a string with the value "java". What will be assigned to x if you execute the followingwill be assigned to x if you execute the following code?
char x = s.charAt(4);
A. 'a'B. 'v'C. Nothing will be assigned to x, because the execution
causes the runtime error StringIndexOutofBoundsExceptionStringIndexOutofBoundsException.
Review questions
• Suppose s1 and s2 are two strings. Which of the following statements or expressions isthe following statements or expressions is incorrect?
A. String s3 = s1 - s2;
B. boolean b = s1.compareTo(s2);
C. char c = s1[0];
D. char c = s1.charAt(s1.length());
Review questions
• Analyze the following code.
class Test {public static void main(String[] args) {
String s;System.out.println("s is " + s);
}}
A. The program has a compilation error because s is not initialized, but it is referenced in the println statement.
B The program has a runtime error because s is not initialized but it isB. The program has a runtime error because s is not initialized, but it is referenced in the println statement.
C. The program has a runtime error because s is null in the println statement.D. The program compiles and runs fine.
Outline
• StringBuilder/StringBuffer class
l l d l /• File class and File I/O
StringBuilder/StringBuffer
• An alternative to the String class – a mutable stringstring
• In general, a StringBuilder/StringBuffer can be d h dused wherever a string is used
• StringBuilder/StringBuffer is more flexible than String
• You can add, insert, or append new contents , , ppinto a string buffer– A String object is fixed once the string is created.
25
A String object is fixed once the string is created.
StringBuilder Constructors
java.lang.StringBuilder
+St i B ild () C i b ild i h i 16+StringBuilder() +StringBuilder(capacity: int) +StringBuilder(s: String)
Constructs an empty string builder with capacity 16.Constructs a string builder with the specified capacity. Constructs a string builder with the specified string.
26
Modifying Strings in the Builder
java.lang.StringBuilder
+append(data: char[]): StringBuilder +append(data: char[] offset: int len: int):
Appends a char array into this string builder. Appends a subarray in data into this string builder.+append(data: char[], offset: int, len: int):
StringBuilder +append(v: aPrimitiveType): StringBuilder +append(s: String): StringBuilder
Appends a subarray in data into this string builder. Appends a primitive type value as a string to this
builder. Appends a string to this string builder.
+delete(startIndex: int, endIndex: int): StringBuilder
+deleteCharAt(index: int): StringBuilder +insert(index: int, data: char[], offset: int,
len: int): StringBuilder
Deletes characters from startIndex to endIndex. Deletes a character at the specified index. Inserts a subarray of the data in the array to the builder
at the specified index. len: int): StringBuilder +insert(offset: int, data: char[]):
StringBuilder +insert(offset: int, b: aPrimitiveType):
StringBuilder
pInserts data into this builder at the position offset. Inserts a value converted to a string into this builder.
+insert(offset: int, s: String): StringBuilder+replace(startIndex: int, endIndex: int, s:
String): StringBuilder +reverse(): StringBuilder +setCharAt(index: int ch: char): void
Inserts a string into this builder at the position offset.
Replaces the characters in this builder from startIndex to endIndex with the specified string.
Reverses the characters in the builder. S t h t t th ifi d i d i thi
27
+setCharAt(index: int, ch: char): void
Sets a new character at the specified index in this builder.
The toString, capacity, length, setLength, and charAt Methods
java.lang.StringBuilder
+toString(): String Returns a string object from the string builder.g() g+capacity(): int +charAt(index: int): char +length(): int
g j gReturns the capacity of this string builder. Returns the character at the specified index. Returns the number of characters in this builder.
+setLength(newLength: int): void +substring(startIndex: int): String +substring(startIndex: int, endIndex: int):
Sets a new length in this builder. Returns a substring starting at startIndex. Returns a substring from startIndex to endIndex-1.
String +trimToSize(): void
Reduces the storage size used for the string builder.
28
Example: Checking Palindromes Using StringBuilder
h l d h h k• Rewrite the palindromes program that checks whether a string is a palindrome by using
ld lStringBuilder class
• CheckPalindromeStringBuilder.java
29
The File Class (another object)
• File class is used to obtain file properties and to d l t d fildelete and rename files
• The File class is intended to provide an abstraction th t d l ith t f th hi d d tthat deals with most of the machine-dependent complexities of files and path names in a machine-independent fashionindependent fashion
• The File class is a wrapper class for the file name and its directory pathand its directory path.
It i t f di d iti fil t tIt is not for reading and writing file contents.
30
Obtaining file properties and manipulating file
java.io.File
+File(pathname: String)
+File(parent: String child: String)
Creates a File object for the specified pathname. The pathname may be a directory or a file.
Creates a File object for the child under the directory parent child may be a+File(parent: String, child: String)
+File(parent: File, child: String)
+exists(): boolean +canRead(): boolean
Creates a File object for the child under the directory parent. child may be a filename or a subdirectory.
Creates a File object for the child under the directory parent. parent is a File object. In the preceding constructor, the parent is a string.
Returns true if the file or the directory represented by the File object exists. Returns true if the file represented by the File object exists and can be read+canRead(): boolean
+canWrite(): boolean +isDirectory(): boolean +isFile(): boolean +isAbsolute(): boolean
Returns true if the file represented by the File object exists and can be read.Returns true if the file represented by the File object exists and can be written.Returns true if the File object represents a directory. Returns true if the File object represents a file. Returns true if the File object is created using an absolute path name.
+isHidden(): boolean
+getAbsolutePath(): String
Returns true if the file represented in the File object is hidden. The exact definition of hidden is system-dependent. On Windows, you can mark a file hidden in the File Properties dialog box. On Unix systems, a file is hidden if its name begins with a period character '.'.
Returns the complete absolute file or directory name represented by the File object
+getCanonicalPath(): String
+getName(): String
object.Returns the same as getAbsolutePath() except that it removes redundant
names, such as "." and "..", from the pathname, resolves symbolic links (on Unix platforms), and converts drive letters to standard uppercase (on Win32 platforms).
Returns the last name of the complete directory and file name represented by
+getPath(): String +getParent(): String
the File object. For example, new File("c:\\book\\test.dat").getName() returns test.dat.
Returns the complete directory and file name represented by the File object. For example, new File("c:\\book\\test.dat").getPath() returns c:\book\test.dat.
Returns the complete parent directory of the current directory or the file represented b the File object For e ample ne
31
+lastModified(): long +delete(): boolean +renameTo(dest: File): boolean
represented by the File object. For example, new File("c:\\book\\test.dat").getParent() returns c:\book.
Returns the time that the file was last modified. Deletes this file. The method returns true if the deletion succeeds. Renames this file. The method returns true if the operation succeeds.
Problem: Explore File Properties
• Let’s test the File class
• TestFileClass.java
32
File I/O
• A File object encapsulates the properties of a file or a path but does not contain the methods for reading/writing data from/to a file
• In order to perform I/O, we need to use I/O classes:In order to perform I/O, we need to use I/O classes: Scanner and PrintWriter
33
Reading data using Scanner class
• Read data from keyboard
Scanner input = new Scanner(System.in);
• Read data from a fileRead data from a file
Scanner input = new Scanner(new File(filename));
Reading Data Using Scanner java.util.Scanner
+Scanner(source: File) Creates a Scanner that produces values scanned from the specified file. +Scanner(source: String) +close() +hasNext(): boolean +next(): String
Creates a Scanner that produces values scanned from the specified string.Closes this scanner. Returns true if this scanner has another token in its input. Returns next token as a string+next(): String
+nextByte(): byte +nextShort(): short +nextInt(): int
Returns next token as a string. Returns next token as a byte. Returns next token as a short. Returns next token as an int.()
+nextLong(): long +nextFloat(): float +nextDouble(): double
Returns next token as a long. Returns next token as a float. Returns next token as a double.
+useDelimiter(pattern: String): Scanner
Sets this scanner’s delimiting pattern.
35
Scanner example
• Reading data from the score file named “scores.txt”
• ReadData.javaReadData.java
Review questions• The following program displays __________.
public class Test {public class Test {public static void main(String[] args) {String s = "Java";StringBuilder buffer = new StringBuilder(s);change(buffer);System.out.println(buffer);
}
private static void change(StringBuilder buffer) {buffer.append(" and HTML");bu e .appe d( a d );
}}
A. JavaB. Java and HTMLC. and HTMLD. nothing is displayed
Homework 5: Breaking the Caesar cipher (due Monday Nov 2 Wed Nov 4)cipher (due Monday Nov 2 Wed Nov 4)
• Problem: given encrypted text file, break the cipher and print the plain-text (original) message to standard output. http://en.wikipedia.org/wiki/Caesar_cipher
• Command line arguments: encrypted text, dictionary file (both file names given from command line).
• Output: original plaintext
• Simplifying assumptions: – No punctuation in input
– All words in plaintext are in dictionary, and are in lower case.
– Dictionary is small (less than 2000 words).
10/28/2009 CS170, Section 000, Fall 2009 38
HW5 (cont’d): Approach
• Overall approach (brute force/dictionary attack)l f d– Assume plain text comes from a dictionary
– Try all possible shifts until each word in a message is found in the dictionarythe dictionary
• Implementation approach:– Read encrypted text from a file, split into words, store into yp , p ,
array of words (separate string/entry for each word)– Read dictionary, store each word (e.g., in array for now), use
i di id l t i f h dindividual string for each word– Write a method to search for a given word from the
encrypted text in the dictionaryyp y• can use linear or binary search, or something else (Thursday lecture)
10/28/2009 CS170, Section 000, Fall 2009 39
HW5 (+5 extra credit)
• Break Viginaire cipher (extension of Caesar)– http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher
– Assume fixed key, length >=5 and <=10
– assume all words are from dictionary (as before)
– Requires repeatedly breaking the Caesar cipher, for each q p y g pkey length, for each possible key (brute force)3
10/28/2009 CS170, Section 000, Fall 2009 40