Tải bản đầy đủ (.pdf) (31 trang)

Lecture Java methods: Object-oriented programming and data structures (2nd AP edition): Chapter 10 - Maria Litvin, Gary Litvin

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (253.36 KB, 31 trang )

Java Methods
Object-Oriented Programming
and Data Structures
2nd AP edition

with GridWorld

Maria Litvin ● Gary Litvin

"Chapter 10"
Strings

Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All
rights reserved.


Objectives:
• Learn about literal strings
• Learn about String constructors and
commonly used methods

• Understand immutability of strings
• Learn to format numbers into strings and
extract numbers from strings

• Learn several useful methods of the
Character class

• Learn about the StringBuffer class
10­2



The String class
• An object of the String class represents a
string of characters.

• The String class belongs to the java.lang
package, which is built into Java.

• Like other classes, String has constructors
and methods.

• Unlike other classes, String has two
operators, + and += (used for concatenation).

10­3


Literal Strings
• Literal strings are anonymous constant
objects of the String class that are defined as
text in double quotes.

• Literal strings don’t have to be constructed:
they are “just there.”

10­4


Literal Strings (cont’d)
• can be assigned to String variables.

• can be passed to methods and constructors
as parameters.

• have methods you can call:
String fileName = "fish.dat";
button = new JButton("Next slide");
if ("Start" equals(cmd)) ...

10­5


Literal Strings (cont’d)
• The string text may include “escape”
characters (described in Section 6.5).
For example:



\\ stands for \
\n stands for newline
String s1 = "Biology”;
String s2 = "C:\\jdk1.4\\docs";
String s3 = "Hello\n";

10­6


Immutability
• Once created, a string cannot be changed:
none of its methods can change the string.


• Such objects are called immutable.
• Immutable objects are convenient because
several references can point to the same
object safely: there is no danger of changing
an object through one reference without the
others being aware of the change.

10­7


Immutability (cont’d)
• Advantage: more efficient, no need to copy.
String s1 = "Sun";
String s2 = s1;
s1

String s1 = "Sun";
String s2 = new String(s1);
s1

"Sun"

s2

"Sun"

"Sun"
s2
OK


Less efficient:
wastes memory
10­8


Immutability (cont’d)
• Disadvantage: less efficient — you need to
create a new string and throw away the old
one for every small change.
String s = "sun";
char ch = Character.toUpperCase(s.charAt (0));
s = ch + s.substring (1);
s

"sun"
"Sun"
10­9


Empty Strings
• An empty string has no characters; its
length is 0.
String s1 = "";
String s2 = new String();

Empty strings

• Not to be confused with an uninitialized
string:

private String errorMsg;

errorMsg
is null

10­10


Constructors
• String’s no-args and copy constructors are
not used much.
String s1 = new String ();

String s1 = "";

String s2 = new String (s1);

String s2 = s1;

• Other constructors convert arrays
(Chapter 12) into strings

10­11


Methods — length, charAt
int length ();
char charAt (k);

• Returns the number of



characters in the string
Returns the k-th char

Character positions in strings
are numbered starting from 0
Returns:
”Flower".length();

6

”Wind".charAt (2);

'n'
10­12


Methods — substring
String s2 = s.substring (i, j);
returns the substring of chars in
positions from i to j-1

strawberry
i

String s2 = s.substring (i);
returns the substring from the i-th
char to the end
”strawberry".substring (2,5);

"unhappy".substring (2);
"emptiness".substring (9);

j

strawberry
i

Returns:
"raw"
"happy"
"" (empty string)
10­13


Methods — Concatenation
String result = s1 + s2;
concatenates s1 and s2

String result = s1.concat (s2);
the same as s1 + s2

result += s3;
concatenates s3 to result

result += num;
converts num to String and concatenates it to
result

10­14



Methods — Find (indexOf)
0

8

11 15

String date ="July 5, 2012 1:28:19 PM";
date.indexOf ('J');

Returns:
0

date.indexOf ('2');

8

date.indexOf ("2012");

8

date.indexOf ('2', 9);

11

date.indexOf ("2020");

-1


date.lastIndexOf ('2');

15

(starts searching
at position 9)
(not found)
10­15


Methods — Comparisons
boolean b = s1.equals(s2);
returns true if the string s1 is equal to s2
boolean b = s1.equalsIgnoreCase(s2);
returns true if the string s1 matches s2, case-blind
int diff = s1.compareTo(s2);
returns the “difference” s1 - s2
int diff = s1.compareToIgnoreCase(s2);
returns the “difference” s1 - s2, case-blind

10­16


Methods — Replacements
String s2 = s1.trim ();
returns a new string formed from s1 by
removing white space at both ends
String s2 = s1.replace(oldCh, newCh);
returns a new string formed from s1 by

replacing all occurrences of oldCh with newCh
String s2 = s1.toUpperCase();
String s2 = s1.toLowerCase();
returns a new string formed from s1 by
converting its characters to upper (lower) case

10­17


Replacements (cont’d)
• Example: how to convert s1 to upper case
s1 = s1.toUpperCase();

• A common bug:
s1.toUpperCase();

s1 remains
unchanged

10­18


Numbers to Strings
• Three ways to convert a number into a
string:
1.
String s = "" + n;
2.
String s = Integer.toString (n);
String s = Double.toString (x);

3.

Integer and Double
are “wrapper” classes
from java.lang that
represent numbers as
objects. They also
provide useful static
methods.

String s = String.valueOf (n);

10­19


Numbers to Strings (cont’d)
• The DecimalFormat class can be used for
formatting numbers into strings.
import java.text.DecimalFormat;
...
DecimalFormat money =
new DecimalFormat("0.00");
...
double amt = 56.7381;
...
String s = money.format (amt);

56.7381
"56.74"


10­20


Numbers to Strings (cont’d)
• Java 5.0 added printf and format methods:
int m = 5, d = 19, y = 2007;
double amt = 123.5;
System.out.printf (
"Date: %02d/%02d/%d Amount = %7.2f\n", m, d, y, amt);
String s = String. format(
"Date: %02d/%02d/%d Amount = %7.2f\n", m, d, y, amt);

Displays,
sets s to:
"Date: 05/19/2007 Amount 123.50"

10­21


Numbers from Strings
String s1 = "-123", s2 = "123.45";
int n = Integer.parseInt(s1);
double x = Double.parseDouble(s2);

• These methods throw a
NumberFormatException if s does not
represent a valid number (integer, real
number, respectively).

10­22



Numbers from Strings (cont’d)
• A safer way:
int n;
do {
try
{
n = Integer.parseInt(s);
}
catch (NumberFormatException ex)
{
System.out.println("Invalid input, reenter");
}
} while (...);
10­23


Character Methods
• java.lang.Character is a “wrapper” class that
represents characters as objects.

• Character has several useful static methods
that determine the type of a character (letter,
digit, etc.).

• Character also has methods that convert a
letter to the upper or lower case.

10­24



Character Methods (cont’d)
if (Character.isDigit (ch)) ...
.isLetter...
.isLetterOrDigit...
.isUpperCase...
.isLowerCase...

Whitespace is
space, tab,
newline, etc.

.isWhitespace...

return true if ch belongs to the corresponding
category

10­25


×