Page 1
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
CS106A,Lecture8CharactersandStrings
suggestedreading:JavaCh.8.1-8.4
Page 2
2
Learning Goals•Beabletoconfidentlywriteandcallmethodsthatuseparametersandreturnvalues.
•Beabletogeneraterandomvaluesinyourprograms.
•Beabletouseandmanipulatechars.•Beabletowritestringalgorithmsthatoperateoneachcharacter.
Page 3
3
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
Page 4
4
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
Page 5
5
Parameters
Parametersletyouprovideamethodsomeinformationwhenyouarecallingit.
Page 6
6
Return
Returnvaluesletyougivebacksomeinformationwhen
amethodisfinished.
Page 7
7
Methods = Toasters
parameter
Page 8
8
Methods = Toasters
parameter
Page 9
9
Methods = Toasters
Page 10
10
Methods = Toasters
Page 11
11
Methods = Toasters
return
Page 12
12
Example: readInt
int x = readInt(”Your guess? ");
Page 13
13
Example: readInt
int x = readInt(”Your guess? ");
We give readInt some information (the text to
print to the user)
We call readInt
Page 14
14
Example: readInt
int x = readInt(”Your guess? ");
When we include values in the parentheses of a method call, this means we are passing them as parameters to this
method.
Page 15
15
Example: readInt
int x = readInt(”Your guess? ");
When finished, readInt gives us information back (the user’s number) and we put it in x.
Page 16
16
Example: readInt
int x = readInt(”Your guess? ");
When we set a variable equal to a method, this tells Java to save the return value of the method in that variable.
Page 17
17
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
Page 18
18
Parameters Example: drawBox
private void drawBox(int width, int height) {// use width and height variables// to draw a box
}
Tells Java this method needs two ints in order to
execute.
Page 19
19
Parameters Example: drawBox
private void drawBox(int width, int height) {// use width and height variables// to draw a box
}
Inside drawBox, refer to the first parameter value
as width…
Page 20
20
Parameters Example: drawBox
private void drawBox(int width, int height) {// use width and height variables// to draw a box
}
…and the second parameter value as height.
Page 21
21
drawBox
drawBox(10, 4);
We give drawBox some information (the size of
the box we want)
We call drawBox
Page 22
22
drawBox
int width = readInt("Width? ");int height = readInt("Height? ");...
drawBox(width, height);
We give drawBox some information (the size of
the box we want)
We call drawBox
Page 23
23
drawBox
int width = readInt("Width? "); 7int height = readInt("Height? "); 4...
drawBox(width, height);
Page 24
24
drawBox
int width = readInt("Width? "); 7int height = readInt("Height? "); 4...
drawBox(width, height);7 4
Page 25
25
drawBox
int width = readInt("Width? "); 7int height = readInt("Height? "); 4...
drawBox(7, 4);
Page 26
26
drawBox
7 4
Second parameter to
drawBox
First parameter to drawBox
Page 27
27
drawBox
private void drawBox(int width, int height) {
7 4
Page 28
28
drawBox
private void drawBox(int width, int height) {// use width and height variables// to draw a box
}
7 4
Page 29
29
drawBox
private void drawBox(int width, int height) {...println(width); // prints 7println(height); // prints 4...
}
7 4
Page 30
30
Parameter Names
Parameternamesdonotaffectprogrambehavior.
Page 31
31
Parameter Namespublic void run() {
int width = readInt("Width? "); 7int height = readInt("Height? "); 4drawBox(width, height);
}
private void drawBox(int width, int height) {...
}
run
width height
7 4drawBox
width height
7 4
Page 32
32
Parameter Namespublic void run() {
int width = readInt("Width? "); 7int height = readInt("Height? "); 4drawBox(width, height);
}
private void drawBox(int w, int h) {...
}
run
width height
7 4drawBox
w h
7 4
Page 33
33
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
Page 34
34
Return Example: metersToCm
private double metersToCm(double meters) {...
}
When this method finishes, it will return a double.
Page 35
35
Return Example: metersToCm
private double metersToCm(double meters) {double centimeters = meters * 100;return centimeters;
}
Returns the value of this expression (centimeters).
Page 36
36
Return Example: metersToCm
public void run() {double cm = metersToCm(10);...
}
Page 37
37
Return Example: metersToCm
public void run() {double cm = metersToCm(10);...
}
Setting a variable equal to a method means we save the method’s return
value in that variable.
Page 38
38
Return Example: metersToCmpublic void run() {
double meters = readDouble("# meters? ”);...
double cm = metersToCm(meters);println(cm + " centimeters.");
}
private double metersToCm(double meters) {double centimeters = meters * 100;return centimeters;
}
Page 39
39
Return Example: metersToCmpublic void run() {
double meters = readDouble("# meters? ”);...
double cm = metersToCm(meters);println(cm + " centimeters.");
}
private double metersToCm(double meters) {double centimeters = meters * 100;return centimeters;
}
7
Page 40
40
Return Example: metersToCmpublic void run() {
double meters = readDouble("# meters? ”);...
double cm = metersToCm(meters);println(cm + " centimeters.");
}
private double metersToCm(double meters) {double centimeters = meters * 100;return centimeters;
}
7
7
Page 41
41
Return Example: metersToCmpublic void run() {
double meters = readDouble("# meters? ”);...
double cm = metersToCm(meters);println(cm + " centimeters.");
}
private double metersToCm(double meters) {double centimeters = meters * 100;return centimeters;
} 700
7
7
Page 42
42
Return Example: metersToCmpublic void run() {
double meters = readDouble("# meters? ”);...
double cm = metersToCm(meters);println(cm + " centimeters.");
}
700
7
Page 43
43
Return Values and Expressionspublic void run() {
double meters = readDouble("# meters? ”);println(metersToCm(meters) + " cm.");
}
private double metersToCm(double meters) {...
}
7
Page 44
44
Return Values and Expressionspublic void run() {
double meters = readDouble("# meters? ”);println(metersToCm(meters) + " cm.");
}
private double metersToCm(double meters) {...
}
700
You can use a method’s return value directly in an expression.
7
Page 45
45
Buggy Example!public void run() {
double meters = readDouble("# meters? ”);...
metersToCm(meters); // Does nothing!...
}
7
Page 46
46
Buggy Example!public void run() {
double meters = readDouble("# meters? ”);...
metersToCm(meters); // Does nothing!...
}
7
700
Page 47
47
private int max(int num1, int num2) {if(num1 >= num2) {
return num1;}return num2; // here only if num1 < num2
}
Return Stops Method Execution
Page 48
48
Returning Booleans
private boolean isEven(int number) {return number % 2 == 0;
}
Page 49
49
Returning Booleans
private boolean isEven(int number) {return number % 2 == 0;
}
56
Page 50
50
Returning Booleans
private boolean isEven(int number) {return number % 2 == 0;
}
56
true
Page 51
51
Returning Booleans
private boolean isEven(int number) {return number % 2 == 0;
}
// Examplepublic void run() {
if (isEven(2)) {...
}}
Page 52
52
Returning Booleans
private boolean isDivisibleBy(int a, int b) {return a % b == 0;
}
Page 53
53
Returning Booleans
private boolean isDivisibleBy(int a, int b) {return a % b == 0;
}
24 9
Page 54
54
Returning Booleans
private boolean isDivisibleBy(int a, int b) {return a % b == 0;
}
24 9
false
Page 55
55
Returning Booleans
private boolean isDivisibleBy(int a, int b) {return a % b == 0;
}
// Examplepublic void run() {
if (isDivisibleBy(4, 2)) {...
}}
Page 56
56
Factorial Code Walkthrough
Seenextslides
Page 57
57
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}i
4
Page 58
58
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0i
Page 59
59
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0i
Page 60
60
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0i
Page 61
61
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0i
Page 62
62
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
result0n i
Page 63
63
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result0n i
Page 64
64
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result0n 1i
Page 65
65
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result0n 1i
Page 66
66
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result0n 1i
Page 67
67
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0i
1
Page 68
68
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0i
1
0! = 1
Page 69
69
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}1i
0! = 1
Page 70
70
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}1i
0! = 1
Page 71
71
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}1i
0! = 1
Page 72
72
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}1i
0! = 1
Page 73
73
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
result1n i
0! = 1
Page 74
74
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result1n i
0! = 1
Page 75
75
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result1n 1i
0! = 1
Page 76
76
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result1n 1i
0! = 1
Page 77
77
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result1n 1i
0! = 1
Page 78
78
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result1n 2i
0! = 1
Page 79
79
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result1n 2i
0! = 1
Page 80
80
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}0
i
private int factorial(int n) {int result = 1;for (int i = 1; i <= n; i++) {
result *= i;}return result;
}
1result1n 2i
0! = 1
Page 81
81
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}1i
1
0! = 1
Page 82
82
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}1i
1
0! = 11! = 1
Page 83
83
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}2i
0! = 11! = 1
Page 84
84
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}2i
0! = 11! = 1
Page 85
85
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}2i
0! = 11! = 1
Page 86
86
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}2i
0! = 11! = 1
Page 87
87
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}2i
2
0! = 11! = 1
Page 88
88
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}2i
2
0! = 11! = 12! = 2
Page 89
89
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}3i
0! = 11! = 12! = 2
Page 90
90
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}3i
0! = 11! = 12! = 2
Page 91
91
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}3i
0! = 11! = 12! = 2
Page 92
92
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}3i
0! = 11! = 12! = 2
Page 93
93
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}3i
6
0! = 11! = 12! = 2
Page 94
94
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}3i
6
0! = 11! = 12! = 23! = 6
Page 95
95
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}4i
0! = 11! = 12! = 23! = 6
Page 96
96
public void run() {for(int i = 0; i < MAX_NUM; i++) {
println(i + "! = " + factorial(i));}
}4i
0! = 11! = 12! = 23! = 6
Page 97
97
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
Page 98
98
RandomGenerator• import acm.util.*;
// random number from 0-9 inclusiveint digit = RandomGenerator.getInstance().nextInt(0, 9);println(digit);
// prints "hello!" between 3-6 timesint times = RandomGenerator.getInstance().nextInt(3, 6);for (int i = 0; i < times; i++) {
println("hello!");}
Method DescriptionRandomGenerator.getInstance().nextInt(min, max) arandomintegerinthe
givenrange,inclusive
Page 99
99
RandomGeneratorThe RandomGenerator class defines the following methods:
int nextInt(int low, int high)Returns a random int between low and high, inclusive.
int nextInt(int n)Returns a random int between 0 and n-1.
double nextDouble(double low, double high)Returns a random double d in the range low ≤ d < high.
double nextDouble()Returns a random double d in the range 0 ≤ d < 1.
boolean nextBoolean()Returns a random boolean value, which is true 50 percent of the time.
boolean nextBoolean(double p)Returns a random boolean, which is true with probability p, where 0 ≤ p ≤ 1.
Color nextColor()Returns a random color.
Page 100
100
Extra: Dice exercise• WriteaconsoleprogramRollTwoDice thatrepeatedlyrollstwo6-sideddiceuntiltheyarriveatagivendesiredsum.
Desired sum? 93 and 4 = 72 and 1 = 35 and 5 = 106 and 2 = 86 and 5 = 114 and 5 = 9
• TrysolvingthisonyourownonCodeStepByStep!
RollTwoDice
Page 101
101
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
Page 102
102
Text Processing
Page 103
103
Goal
After learning text processing, we will be able to write our own encryption program!
Page 104
104
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
Page 105
105
CharAchar isavariabletypethatrepresentsasinglecharacteror“glyph”.
char letterA = 'A';char plus = '+';char zero = '0';char space = ' ';char newLine = '\n';char tab = '\t';char singleQuote = '\'';char backSlash = '\\';
Page 106
106
CharUnderthehood,Javarepresentseachchar asaninteger (its“ASCIIvalue”).
•Uppercaselettersaresequentiallynumbered•Lowercaselettersaresequentiallynumbered•Digitsaresequentiallynumbered
char uppercaseA = 'A'; // Actually 65char lowercaseA = 'a'; // Actually 97char zeroDigit = '0'; // Actually 48
Page 107
107
Char Math!WecantakeadvantageofJavarepresentingeachchar asaninteger (its“ASCIIvalue”):
boolean areEqual = 'A' == 'A'; // trueboolean earlierLetter = 'f' < 'c'; // falsechar uppercaseB = 'A' + 1;int diff = 'c' - 'a'; // 2int numLettersInAlphabet = 'z' – 'a' + 1;// orint numLettersInAlphabet = 'Z' – 'A' + 1;
Page 108
108
Char Math!WecantakeadvantageofJavarepresentingeachchar asaninteger (its“ASCIIvalue”):
// prints out every characterfor (char ch = 'a'; ch <= 'z'; ch++) {
print(ch);}
Page 109
109
Char Math!Noteveryintegermapstoacharacter.Sowhenyouhaveanexpressionwithints andchars,Javapicksint asthemostexpressivetype.
'A' + 1 // evaluates to 66 (int)'c' + (2*5) – 1 // evaluates to 108
Wecanmakeitacharbyputtingitinacharvariable.char uppercaseB = 'A' + 1;// orchar uppercaseB = 66;
Page 110
110
Side Note: Type-castingIfwewanttoforceJavatotreatanexpressionasaparticulartype,wecanalsocastit tothattype.
'A' + 1 // evaluates to 66 (int)(char)('A' + 1) // evaluates to 'B' (char)
1 / 2 // evaluates to 0 (int)(double)1 / 2 // evaluates to 0.5 (double)1 / (double)2 // evaluates to 0.5 (double)
Page 111
111
Character MethodsTherearesomehelpfulbuilt-inJavamethodstomanipulatechars.
char lowercaseA = 'a';char uppercaseA = Character.toUpperCase(lowercaseA);
char plus = '+';if (Character.isLetter(plus)) {
...}
Page 112
112
Character MethodsMethod Description
Character.isDigit(ch) trueifch is'0' through'9'
Character.isLetter(ch) trueifch is'a' through'z' or'A' through'Z'
Character.isLetterOrDigit(ch) trueifch is'a' through'z','A' through'Z' or '0' through'9'
Character.isLowerCase(ch) trueifch is'a' through'z'
Character.isUpperCase(ch) trueifch is'A' through'Z'
Character.toLowerCase(ch) returnslowercaseequivalentofaletter
Character.toUpperCase(ch) returnsuppercaseequivalentofaletter
Character.isWhitespace(ch) trueifch isaspace,tab,newline,etc.
Remember: these returnthe new char, they cannot modify an existing char!
Page 113
113
Character MethodsRemembertoalwayssavethereturnvalueofCharactermethods!
char lowercaseA = 'a';Character.toUpperCase(lowercaseA); // Does nothing!println(lowercaseA); // prints ’a’!
char uppercaseA = Character.toUpperCase(lowercaseA); // OK
println(uppercaseA); // prints ’A’!
Page 114
114
Plan For Today•Announcements•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
Page 115
115
StringsAString isavariabletyperepresentingasequenceofcharacters.
String text = "Hi parents!";
– Eachcharacterisassignedanindex,goingfrom0tolength-1– Thereisachar ateachindex
index 0 1 2 3 4 5 6 7 8 9 10
character 'H' 'i' ' ' 'p' 'a' 'r' 'e' 'n' 't' 's' '!'
Page 116
116
String str = "Hello, world!";String empty = "";println(str);
// Read in text from the userString name = readLine("What is your name? ");
// String concatenation (using “+”)String message = 2 + " cool " + 2 + " handle";int x = 2;println("x has the value " + x);
Creating Strings
Page 117
117
String str = "Hello, world!";
// Lengthint strLength = str.length(); // 13
// Access individual characterschar firstLetter = str.charAt(0);char lastLetter = str.charAt(strLength – 1);char badTimes = str.charAt(strLength); // ERROR
Common String Operations
Page 118
118
SubstringsAsubstring isasubsetofastring.
String str = "Hello, world!";String hello = str.substring(0, 5);
0 1 2 3 4 5 6 7 8 9 10 11 12'H' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!'
Page 119
119
SubstringsAsubstring isasubsetofastring.
String str = "Hello, world!";String worldExclm = str.substring(7, 13);
0 1 2 3 4 5 6 7 8 9 10 11 12'H' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!'
Page 120
120
SubstringsAsubstring isasubsetofastring.
String str = "Hello, world!";String worldExclm = str.substring(7); // to end
0 1 2 3 4 5 6 7 8 9 10 11 12'H' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!'
Page 121
121
String MethodsMethodname Description
s.length() numberofcharactersinthisstring
s.charAt(index) charatthegivenindex
s.indexOf(str) indexwherethestartofthegivenstringappearsinthisstring(-1ifnotfound)
s.substring(index1, index2)ors.substring(index1)
thecharactersinthisstringfromindex1 (inclusive)toindex2 (exclusive);ifindex2 isomitted,goesuntilend
s.toLowerCase() anewstringwithalllowercaseletterss.toUpperCase() anewstringwithalluppercaseletters
• Thesemethodsarecalledusingdotnotation:
String className = "CS 106A yay!";println(className.length()); // 12
Page 122
122
Strings are ImmutableOnceyoucreateaString,itscontentscannotbechanged.
// Cannot change individual chars in the stringString typo = "Hello, warld!”;
TochangeaString,youmustcreateanew Stringcontainingthevalueyouwant(e.g.usingStringmethods).
Page 123
123
Strings are ImmutableString className = "cs 106a";className.toUpperCase(); // does nothing!
className = className.toUpperCase(); // ✔println(className); // CS 106A
Page 124
124
Comparing StringsString greeting = "Hello!”;if (greeting == "Hello!") { // Doesn’t work!
...}
// Instead:if (greeting.equals("Hello!")) {
...}
Always use .equals instead of == and !=
Page 125
125
Comparing StringsMethod Description
s1.equals(s2) whethertwostringscontainthesamecharacters
s1.equalsIgnoreCase(s2) whethertwostringscontainthesamecharacters,ignoringuppervs.lowercase
s1.startsWith(s2) whethers1 containss2’scharactersatstart
s1.endsWith(s2) whethers1 containss2’scharactersatend
s1.contains(s2) whethers2 isfoundwithins1
Page 126
126
Looping Over StringsAcommonStringprogrammingpatternisloopingoverastringandoperatingoneachcharacter.
String str = "Hello!";for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);// Do something with ch here
}
Page 127
127
Looping Over StringsAcommonStringprogrammingpatternisloopingoverastringandoperatingoneachcharacter.
// Prints out each letter on a separate lineString str = "Hello!";for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);println(ch);
}
Page 128
128
Looping Over StringsAcommonStringprogrammingpatternisloopingoverastringandoperatingoneachcharacter.
// Creates a new String in all capsString str = "Hello!";String newStr = "";for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);newStr += Character.toUpperCase(ch);
}println(newStr); // HELLO!
Page 129
129
Recap•Recap–Parameters–Return
•RandomNumbers•TextProcessing–Characters–Strings
Nexttime:problem-solvingwithStrings