Java Methods A & AB

Download Report

Transcript Java Methods A & AB

String Class in Java
• java.lang
Class String
• java.lang.Object java.lang.String
• We do not have to import the String class
since it comes from java.lang.
• An object of the String class represents a
string of characters. “abcde”;
Two ways to create a String object
• Create a String literal:
String str = "abc";
• With the key word new since it is an object
String str = new String(“abc”);
Empty Strings
• An empty string has no characters;
• Its contents are “null”.
String s1 = “";
String s2 = new String();
Empty strings
10-3
String indexes
• String is a sequence of characters.
Each letter in the string has its own index
location and can be accessed by it.
index location
0
1
c
o
2
m
3
4
p
u
5
t
6
e
7
r
The length of the String is how many letters it contains:
The last index of the String is length – 1;
7
8
10-4
Index locations
Index locations are from 0 to length-1
String s = “strawberry”;
strawberry // 10 letters in the word
// index from 0 to 9
int len = s.length()
// 10
int lastIndex = s.length()-1
//9
S is the String object I created. Objects call
methods with a dot operator.
10-5
String Methods:
• Page 78
• There are many ways to manipulate Strings.
• Look on page 78 those tested on AP
• You always use the period to separate the
object from the method.
• int len = s1.length();
10-6
Methods — length()
int length ();
returns an int
• Returns the number of
characters in the string
String f = “Flower”;
String w = “Wind”;
Returns:
int lenF = f.length();
6
int lenW = w.length();
4
10-7
Methods — substring
Strings have index locations
from 0 to length-1
String s2 = s.substring (i, k);
returns the substring of chars in
positions from i to k-1
strawberry
i
k
String s3 = s.substring (i);
strawberry
returns the substring from i char to
i
the end
String s = “strawberry”;
Returns:
String s2 = s.substring (2,5); start at 2 end at 4 raw
String s3 = s.substring (2); start at 2 thru end rawberry
10-8
String n = “computer";
0
c
1
o
2
m
3
p
4
u
5
t
String one = n.substring(0,7);
String two = n.substring(1,6);
String three = n.substring(2,5);
String four = n.substring(4);
String five = n.substring(3);
6
e
7
r
s.substring(i, k);
returns the substring of
chars in positions from i
to k-1
s.substring(i);
returns the substring
from i char to the end
String six = n.substring(1,n.length()-2);
String seven = six.substring(0, n.length()/2);
10-9
Methods — Concatenation
String s1 = “obi”;
String s2 = “wan”;
String result = s1 + s2;
obiwan
String result = s1.concat (s2);
the same as s1 + s2
obiwan
10-10
Methods — Find (indexOf)
Index of return the index location of the first occurrence of the character
requested.
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-11