Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
CS106A,Lecture9Problem-SolvingwithStrings
suggestedreading:JavaCh.8.5
2
Learning Goals•Beabletowritestringalgorithmsthatoperateoneachcharacter.
•Beabletobuildupnewstringsfromexistingstringsusingbuilt-inStringmethods.
3
Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher
4
Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher
5
Text Processing
6
CharAchar isavariabletypethatrepresentsasinglecharacteror“glyph”.
char letterA = 'A';char plus = '+';char zero = '0';char space = ' ';char newLine = '\n';char tab = '\t';char singleQuote = '\'';char backSlash = '\\';
7
CharUnderthehood,Javarepresentseachchar asaninteger (its“ASCIIvalue”).
•Uppercaselettersaresequentiallynumbered•Lowercaselettersaresequentiallynumbered•Digitsaresequentiallynumbered
char uppercaseA = 'A'; // Actually 65char lowercaseA = 'a'; // Actually 97char zeroDigit = '0'; // Actually 48
8
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;
9
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)
10
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!
11
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' '!'
12
Remember:charsandlength-1stringsaredifferent!
char ch = 'A' DIFFERENT FROM String str = "A"
Strings vs. Chars
13
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
14
char c1 = 'a';char c2 = 'b';
// How do we concatenate these characters?
String str = c1 + c2; // ERROR: this is an int!
String str = "" + c1 + c2; // ✔
From Chars to Strings
15
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
16
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' '!'
17
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' '!'
18
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
19
Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher
20
Looping Over StringsAcommonStringprogrammingpatternisloopingoverastringandoperatingoneachcharacter.
String str = "Hello!";for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);// Do something with ch here
}
21
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);
}
22
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 = newStr + Character.toUpperCase(ch);
}println(newStr); // HELLO!
23
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!
24
Building Up New StringsAnothercommonStringprogrammingpatternisbuildingupanewstringbyaddingcharacterstoitovertime.
// Creates a new String in all capsString str = "";for (int i = 0; i < 5; i++) {
str += i;}println(str); // 01234
25
Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher
26
Exercise: Reversing a StringLet’swriteamethodcalledreverseString thattakesoneStringparameter,andreturnsanewStringwiththecharactersintheoppositeorder.
reverseString("Hello!") -> "!olleH"
27
H e l l o !
Reversing a String
28
H e l l o !
!
Reversing a String
29
H e l l o !
!
Reversing a String
30
H e l l o !
! o
Reversing a String
31
H e l l o !
! o
Reversing a String
32
H e l l o !
! o l
Reversing a String
33
H e l l o !
! o l
Reversing a String
34
H e l l o !
! o l l
Reversing a String
35
H e l l o !
! o l l
Reversing a String
36
H e l l o !
! o l l e
Reversing a String
37
H e l l o !
! o l l e
Reversing a String
38
H e l l o !
! o l l e H
Reversing a String
39
H e l l o !
! o l l e H
Reversing a String
40
Reversing a StringString str = "Hello!";String newStr = "";for (??? ; ??? ; ???) {
...}
41
Reversing a StringString str = "Hello!";String newStr = "";for (int i = str.length() - 1; ??? ; ???) {
...}
H e l l o !
!
42
Reversing a StringString str = "Hello!";String newStr = "";for (int i = str.length() - 1; i >= 0; ???) {
...}
! o l l e H
H e l l o !
43
Reversing a StringString str = "Hello!";String newStr = "";for (int i = str.length() - 1; i >= 0; i--) {
...}
! o l l e H
H e l l o !
44
Reversing a StringString str = "Hello!";String newStr = "";for (int i = str.length() - 1; i >= 0; i--) {
newStr += str.charAt(i);}
45
H e l l o !
Reversing a String
46
H e l l o !
H
Reversing a String
47
H e l l o !
He
Reversing a String
48
H e l l o !
Hel
Reversing a String
49
H e l l o !
Hell
Reversing a String
50
H e l l o !
Hello
Reversing a String
51
H e l l o !
Hello!
Reversing a String
52
Reversing a Stringpublic void run() {
println("This program reverses a string.");String str = readLine("Enter a string: ");String rev = reverseString(str);println(str + " spelled backwards is " + rev);
}
ReverseString
str
STRESSED
This program reverses a string.
STRESSED spelled backwards is DESSERTSSTRESSEDEnter a string:
rev
DESSERTS
private String reverseString(String str) {String result = "";for ( int i = 0; i < str.length(); i++ ) {
result = str.charAt(i) + result;}return result;
}
istrresult
STRESSED 012345678STSRTSERTSSERTSSSERTSESSERTSDESSERTS
Using portions of slides by Eric Roberts
53
Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher
54
Exercise: PalindromesLet’swriteamethodcalledisPalindrome thattakesoneStringparameter,andreturnswhetherornotthatStringisapalindrome(thesameforwardsandbackwards).
isPalindrome("racecar") -> trueisPalindrome("hi there") -> falseisPalindrome("kayak") -> true
55
Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher
56
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
D E F G H I J K L M N O P Q R S T U V W X Y Z A B C
• Rotatealphabetbyn letters(n =3inbelow)– n iscalledthekey
• Wrap-aroundattheend
• Substitutelettersbasedonthismapping
original
encrypt
Exercise: Caesar Cipher
57
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
D E F G H I J K L M N O P Q R S T U V W X Y Z A B C
• Rotatealphabetbyacertainkey,withwrapping
original
encrypt
Exercise: Caesar Cipher
58
Recap•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher
Nexttime:readingtextfiles