csc 204 - programming i lecture 9 september 11, 2002

26
CSC 204 - Programming I Lecture 9 September 11, 2002

Upload: christal-cole

Post on 21-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CSC 204 - Programming I Lecture 9 September 11, 2002

CSC 204 - Programming I

Lecture 9September 11, 2002

Page 2: CSC 204 - Programming I Lecture 9 September 11, 2002

Java’s String Class The Java API provides a huge number of

prewritten classes. Of these, the String class is probably the most important.

Instances of the String class represent strings of characters.

The String class belongs to a package named java.lang.

The java.lang package is automatically imported into every program. (No other package has this property.)

Page 3: CSC 204 - Programming I Lecture 9 September 11, 2002

Creating Strings In Java, every string of characters, such as "abc", is an instance of the String class.

String variables can be assigned String objects as their values:

String str1, str2;

String is the only class whose instances can be created without the word new:

str1 = "abc";

This is an example of magic.

Page 4: CSC 204 - Programming I Lecture 9 September 11, 2002

Visualizing a String A String object can be visualized as a

series of characters, with each character identified by its position.

The first character is located at position 0. A visual representation of the string "Java rules!":

J

0

a

1

v

2

a

3 4

r

5

u

6

l

7

e

8

3

9

!

10

Page 5: CSC 204 - Programming I Lecture 9 September 11, 2002

Common String Methods The String class has a large number of

instance methods. Assume that the following variable

declarations are in effect:String str1 = "Fat cat", str2;

char ch;

int index;

The charAt method returns the character stored at a specific position in a string:ch = str1.charAt(0); // Value of ch is now 'F'

ch = str1.charAt(6); // Value of ch is now 't'

Page 6: CSC 204 - Programming I Lecture 9 September 11, 2002

Common String Methods One version of the indexOf method searches

for a string (the “search key”) within a larger string, starting at the beginning of the larger string.

Example: Locating the string "at" within str1:

index = str1.indexOf("at");

After this assignment, index will have the value 1.

If "at" had not been found anywhere in str1, indexOf would have returned –1.

Page 7: CSC 204 - Programming I Lecture 9 September 11, 2002

Common String Methods The other version of indexOf begins the

search at a specified position, rather than starting at position 0.

This version is particularly useful for repeating a previous search to find another occurrence of the search key.

Example: Finding the second occurrence of "at" in str1:

index = str1.indexOf("at", index + 1);

index will be assigned the value 5.

Page 8: CSC 204 - Programming I Lecture 9 September 11, 2002

Common String Methods lastIndexOf is similar to indexOf, except

that searches proceed backwards, starting from the end of the string.

Example: Finding the last occurrence of "at" in str1:

index = str1.lastIndexOf("at");

The value of index after the assignment will be 5.

Page 9: CSC 204 - Programming I Lecture 9 September 11, 2002

Common String Methods The second version of lastIndexOf begins the

search at a specified position. Example: Finding the next-to-last occurrence

of "at":index = str1.lastIndexOf("at", index - 1);

The value of index after the assignment will be 1.

The String class has additional versions of indexOf and lastIndexOf, whose first argument is a single character rather than a string.

Page 10: CSC 204 - Programming I Lecture 9 September 11, 2002

Common String Methods The length method returns the number of

characters in a string. For example, str1.length() returns the

length of str1, which is 7.

Page 11: CSC 204 - Programming I Lecture 9 September 11, 2002

Common String Methods The substring method returns a substring: a series of consecutive characters within a string.

One version of substring selects a portion of a string beginning at a specified position:str2 = str1.substring(4);

After the assignment, str2 will have the value "cat".

Page 12: CSC 204 - Programming I Lecture 9 September 11, 2002

Common String Methods The other version of substring accepts

two arguments: The position of the first character to include in

the substring The position of the first character after the end

of the substring Example:

str2 = str1.substring(0, 3);

After the assignment, str2 will have the value "Fat".

Page 13: CSC 204 - Programming I Lecture 9 September 11, 2002

Common String Methods toLowerCase and toUpperCase will convert

the letters in a string to lowercase or uppercase.

After the assignmentstr2 = str1.toLowerCase(); //"fat cat".

After the assignmentstr2 = str1.toUpperCase(); //"FAT CAT".

Characters other than letters aren’t changed by toLowerCase and toUpperCase.

Page 14: CSC 204 - Programming I Lecture 9 September 11, 2002

Common String Methods The trim method removes spaces (and

other invisible characters) from both ends of a string.

After the assignmentsstr1 = " How now, brown cow? ";str2 = str1.trim();

the value of str2 will be"How now, brown cow?"

Page 15: CSC 204 - Programming I Lecture 9 September 11, 2002

Chaining Calls of Instance Methods When an instance method returns an

object, that object can be used to call another instance method.

For example, the statementsstr2 = str1.trim();str2 = str2.toLowerCase();

can be combined into a single statement:str2 = str1.trim().toLowerCase();

Page 16: CSC 204 - Programming I Lecture 9 September 11, 2002

Using + to Concatenate Strings One of the most common string operations is concatenation: joining two strings together to form a single string.

The String class provides a concat method that performs concatenation, but it’s rarely used.

Concatenation is so common that Java allows the use of the plus sign (+) to concatenate strings:

str2 = str1 + "s";

str2 now contains the string "Fat cats".

Page 17: CSC 204 - Programming I Lecture 9 September 11, 2002

Using + to Concatenate Strings The + operator works even if one of the

operands isn’t a String object. The non-String operand is converted to string form automatically:System.out.println("Celsius equivalent: " +

celsius);

Page 18: CSC 204 - Programming I Lecture 9 September 11, 2002

Using + to Concatenate Strings If the + operator is used to combine a

string with any other kind of object, the object’s toString method is called.

The statementSystem.out.println("Value of fraction: " + f);

has the same effect asSystem.out.println("Value of fraction: " +

f.toString());

Page 19: CSC 204 - Programming I Lecture 9 September 11, 2002

Using + to Concatenate Strings In order for the + operator to mean string

concatenation, at least one of its two operands must be a string:System.out.println("Java" + 1 + 2); // Prints "Java12"System.out.println(1 + 2 + "Java"); // Prints "3Java"

Page 20: CSC 204 - Programming I Lecture 9 September 11, 2002

Using + to Concatenate Strings The + operator is useful for breaking up

long strings into smaller chunks:System.out.println(

"Bothered by unsightly white space? " + "Remove it quickly and\neasily with " + "the new, improved trim method!");

Page 21: CSC 204 - Programming I Lecture 9 September 11, 2002

Using + to Concatenate Strings The += operator can be used to add

characters to the end of a string:String str = "The quick brown fox ";str += "jumped over ";str += "the lazy dog.";

The final value of str will be "The quick brown fox jumped over the lazy dog."

Concatenating a number with an empty string will convert the number to string form. For example, if i contains 37, then i + "" is the string "37".

Page 22: CSC 204 - Programming I Lecture 9 September 11, 2002

Program: Decoding a VIN Number The manufacturer of a vehicle assigns it a

unique identifying number, called the Vehicle Identification Number (VIN). A VIN packs a large amount of information into a 17-character string:

J H M CB765 8 L C 056658

Page 23: CSC 204 - Programming I Lecture 9 September 11, 2002

The Check Digit in a VIN The check digit in a VIN is computed from

the other characters in the VIN; its purpose is to help detect errors.

The check digit algorithm used in vehicle identification numbers will catch most common errors, such as a single incorrect character or a transposition of two characters.

Page 24: CSC 204 - Programming I Lecture 9 September 11, 2002

The VIN Program The VIN program will split a VIN into its

constituent pieces. The VIN is entered by the user when prompted:Enter VIN: JHMCB7658LC056658World manufacturer identifier: JHMVehicle description section: CB765Check digit: 8Vehicle identification section: LC056658

Page 25: CSC 204 - Programming I Lecture 9 September 11, 2002

// Displays information from a VIN entered by the user

import jpb.*;

public class VIN { public static void main(String[] args) { // Prompt the user to enter a VIN SimpleIO.prompt("Enter VIN: "); String vin = SimpleIO.readLine();

// Extract the parts of the VIN String manufacturer = vin.substring(0, 3); String description = vin.substring(3, 8); String checkDigit = vin.substring(8, 9); String identification = vin.substring(9);

VIN.java

Page 26: CSC 204 - Programming I Lecture 9 September 11, 2002

// Display the parts of the VIN System.out.println("World manufacturer identifier: " + manufacturer); System.out.println("Vehicle description section: " + description); System.out.println("Check digit: " + checkDigit); System.out.println("Vehicle identification section: " + identification); }}