0% found this document useful (0 votes)
10 views67 pages

Lab 5

Uploaded by

ariba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views67 pages

Lab 5

Uploaded by

ariba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

String Processing

Lecture 14

CS106A, Summer 2019


Sarai Gould && Laura Cruz-Albrecht
With inspiration from slides created by Keith Schwarz, Mehran Sahami, Eric Roberts, Stuart Reges, Chris Piech and others.
Announcements
● Assignment 3 due tomorrow at 10AM
● Midterm: check out website page
○ download Bluebook, be sure to have 2 factor authentication with
passcodes; see yesterday’s lecture for helpful links.
○ Midterm conflicts: was due last night, if for some reason you
haven’t done it, please do so now:
http://bit.ly/CS106AMidtermConflicts
● Midterm review session: Friday 10:30AM in Gates B01
● Reminder: schedule has code + suggested readings
○ For today, blank code has been posted so you can code along in
lecture if you would like
2
Learning Goals Today
● Be able to write string algorithms that operate on each
character.
● Be able to build up new strings from existing strings using
built-in String methods.

3
Plan for Today

● Review: Characters and Strings


● Looping over Strings
● Practice: Reversing a String
● Practice: Palindromes
● Practice: Caesar Cipher

4
Plan for Today

● Review: Characters and Strings


● Looping over Strings
● Practice: Reversing a String
● Practice: Palindromes
● Practice: Caesar Cipher

5
Text Processing

6
Characters
A char is a variable type that represents a single character or “glyph”.

Single quotes!

char letterA = 'A';

7
An Aside

8
Char
Under the hood, Java represents each char as an integer.
This integer is its “ASCII” value.

9
Char
Under the hood, Java represents each char as an integer.
This integer is its “ASCII” value.

char uppercaseA = 'A'; // Actually 65


char lowercaseA = 'a'; // Actually 97
char zeroDigit = '0'; // Actually 48

10
Char
Under the hood, Java represents each char as an integer.
This integer is its “ASCII” value.

char uppercaseA = 'A'; // Actually 65


char lowercaseA = 'a'; // Actually 97
char zeroDigit = '0'; // Actually 48

● Uppercase letters ('A' -> 'Z') are sequentially numbered


● Lowercase letters ('a' -> 'z') are sequentially numbered
● Digits ('0' -> '9') are sequentially numbered
11
Char Math
We can take advantage of Java representing each char as
an integer (its “ASCII” value).

boolean areEqual = 'A' == 'A'; // true


boolean earlierLetter = 'f' < 'c'; // false
char uppercaseB = 'A' + 1; // 'B'
int diff = 'c' - 'a'; // 2

int alphabetSize = 'z' – 'a' + 1;


// or
int alphabetSize = 'Z' – 'A' + 1;
12
Type-Casting
If we want to force Java to treat an expression as a particular
type, we can also cast it to that type.

'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)

13
Character Methods

Remember: these
return a new char,
they cannot modify
an existing char.

14
Strings
Text is stored using the variable type String.
A String is a sequence of characters!
Double quotes!

String text = “Hello!”;

15
Strings
● Each character is assigned an index, going from 0 to length-1.
● There is a char at each index.

H e l l o !
0 1 2 3 4 5

int strLen = text.length(); // 6


char last = text.charAt(strLen - 1); // ‘!’
16
Strings vs. Chars

Remember: chars and length-1 Strings are different!

char ch = 'A' DIFFERENT FROM String str = “A”

'A' + 1 // evaluates to 66 (int)


“A” + 1 // evaluates to “A1” (String)

17
Creating Strings
String str = "Hello, world!";
String empty = "";

// Read in text from the user


String name = readLine("What is your name? ");

// String concatenation (using “+”)


String message = name + " is " + 2 + " cool.";

18
From Chars to Strings
char c1 = 'a';
char c2 = 'b';

// How do we concatenate these characters?

String str = c1 + c2; // ERROR: this is an int!

19
From Chars to Strings
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; // ✔

20
Substrings
A substring is a subset of a string.

String str = “Hi Duke!”;


String hi = str.substring(0, 2);

'H' 'i' ' ' 'D' 'u' 'k' 'e' '!'


0 1 2 3 4 5 6 7

21
Substrings
A substring is a subset of a string.

String str = “Hi Duke!”;


String dukeExclm = str.substring(3); // to end

'H' 'i' ' ' 'D' 'u' 'k' 'e' '!'


0 1 2 3 4 5 6 7

22
Useful String Methods

* remember, called using dot notation: myString.length() 23


Strings are Immutable
● Java strings are immutable: once you create a String, its
contents cannot be changed.
● To change a String, you must create a new String containing
the value you want (e.g. using String methods).

String typo = "Hello, warld!”;

typo.charAt(8) = ‘o’; // Error! Will not run.

String corrected = typo.substring(0, 8) +


‘o’ + typo.substring(9);
24
Comparing Strings

Always use .equals() instead of == and !=

25
Plan for Today

● Review: Characters and Strings


● Looping over Strings
● Practice: Reversing a String
● Practice: Palindromes
● Practice: Caesar Cipher

26
Looping over Strings
A common String programming pattern is looping over a
String and operating on each character.

for (int i = 0; i < str.length(); i++) {


char ch = str.charAt(i);
// do something with ch here
}

27
Looping over Strings
A common String programming pattern is looping over a
String and operating on each character.

// prints out each letter on a separate line


for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
println(ch);
}

28
Looping over Strings
Another common String programming pattern is building up a
new string by adding characters to it over time.

// Creates a new String in all caps


String 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!
29
Looping over Strings
Another common String programming pattern is building up a
new string by adding characters to it over time.

// Creates a new String in all caps


String str = "Hello!";
String newStr = "";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
newStr += Character.toUpperCase(ch);
}
println(newStr); // HELLO!
30
Looping over Strings
Another common String programming pattern is building up a
new string by adding characters to it over time.

// Creates a new String containing digits 0 through 4


String str = "";
for (int i = 0; i < 5; i++) {
str += i;
}
println(str); // 01234

31
Plan for Today

● Review: Characters and Strings


● Looping over Strings
● Practice: Reversing a String
● Practice: Palindromes
● Practice: Caesar Cipher

32
Exercise: Reversing a String
Let’s write a method called reverseString that takes one
String parameter, and returns a new String with the
characters in the opposite order.

reverseString("Hello!") -> "!olleH"

33
Reversing a String

H e l l o !

34
Reversing a String

H e l l o !

35
Reversing a String

H e l l o !
!
36
Reversing a String

H e l l o !
!
37
Reversing a String

H e l l o !
! o
38
Reversing a String

H e l l o !
! o
39
Reversing a String

H e l l o !
! o l
40
Reversing a String

H e l l o !
! o l
41
Reversing a String

H e l l o !
! o l l
42
Reversing a String

H e l l o !
! o l l
43
Reversing a String

H e l l o !
! o l l e
44
Reversing a String

H e l l o !
! o l l e
45
Reversing a String

H e l l o !
! o l l e H
46
Reversing a String

H e l l o !
! o l l e H
47
Another Take

48
Reversing a String

H e l l o !

49
Reversing a String

H e l l o !
H
50
Reversing a String

H e l l o !
e H
51
Reversing a String

H e l l o !
l e H
52
Reversing a String

H e l l o !
l l e H
53
Reversing a String

H e l l o !
o l l e H
54
Reversing a String

H e l l o !
! o l l e H
55
Plan for Today

● Review: Characters and Strings


● Looping over Strings
● Practice: Reversing a String
● Practice: Palindromes
● Practice: Caesar Cipher

56
Exercise: Palindromes
Let’s write a method called isPalindrome that takes one
String parameter, and returns whether or not that String is a
palindrome (the same forwards and backwards)

isPalindrome("racecar") -> true


isPalindrome("hi there") -> false
isPalindrome("kayak") -> true
57
Let’s Code It!

58
More Palindromes

Here are some palindromes in other languages:

● ‫( ب ﻗﻠﻌﺔ ﺗﺣت ﺗﻌﻠق ﺑﻠﺢ‬Dates hang underneath a castle in Halab)


● 여보 , 안경 안보여 (Honey, I can't see my glasses)
● कड़क (a loud thunderous sound)
● 上海自來水來自海上 (Shanghai tap water originates from "above"
the ocean)

Do you know a palindrome in another language?

59
Stress Test
A man, a plan, a caret, a ban, a myriad, a sum, a lac, a liar, a hoop, a pint, a catalpa, a gas, an oil, a bird, a
yell, a vat, a caw, a pax, a wag, a tax, a nay, a ram, a cap, a yam, a gay, a tsar, a wall, a car, a luger, a ward,
a bin, a woman, a vassal, a wolf, a tuna, a nit, a pall, a fret, a watt, a bay, a daub, a tan, a cab, a datum, a gall,
a hat, a tag, a zap, a say, a jaw, a lay, a wet, a gallop, a tug, a trot, a trap, a tram, a torr, a caper, a top, a tonk,
a toll, a ball, a fair, a sax, a minim, a tenor, a bass, a passer, a capital, a rut, an amen, a ted, a cabal, a tang, a
sun, an ass, a maw, a sag, a jam, a dam, a sub, a salt, an axon, a sail, an ad, a wadi, a radian, a room, a rood, a
rip, a tad, a pariah, a revel, a reel, a reed, a pool, a plug, a pin, a peek, a parabola, a dog, a pat, a cud, a nu, a
fan, a pal, a rum, a nod, an eta, a lag, an eel, a batik, a mug, a mot, a nap, a maxim, a mood, a leek, a grub, a
gob, a gel, a drab, a citadel, a total, a cedar, a tap, a gag, a rat, a manor, a bar, a gal, a cola, a pap, a yaw, a
tab, a raj, a gab, a nag, a pagan, a bag, a jar, a bat, a way, a papa, a local, a gar, a baron, a mat, a rag, a
gap, a tar, a decal, a tot, a led, a tic, a bard, a leg, a bog, a burg, a keel, a doom, a mix, a map, an atom, a
gum, a kit, a baleen, a gala, a ten, a don, a mural, a pan, a faun, a ducat, a pagoda, a lob, a rap, a keep, a
nip, a gulp, a loop, a deer, a leer, a lever, a hair, a pad, a tapir, a door, a moor, an aid, a raid, a wad, an alias,
an ox, an atlas, a bus, a madam, a jag, a saw, a mass, an anus, a gnat, a lab, a cadet, an em, a natural, a tip, a
caress, a pass, a baronet, a minimax, a sari, a fall, a ballot, a knot, a pot, a rep, a carrot, a mart, a part, a tort, a
gut, a poll, a gateway, a law, a jay, a sap, a zag, a tat, a hall, a gamut, a dab, a can, a tabu, a day, a batt, a
waterfall, a patina, a nut, a flow, a lass, a van, a mow, a nib, a draw, a regular, a call, a war, a stay, a gam, a
yap, a cam, a ray, an ax, a tag, a wax, a paw, a cat, a valley, a drib, a lion, a saga, a plat, a catnip, a pooh, a
rail, a calamus, a dairyman, a bater, a canal – Panama!
60
Plan for Today

● Review: Characters and Strings


● Looping over Strings
● Practice: Reversing a String
● Practice: Palindromes
● Practice: Caesar Cipher

61
Exercise: Caesar Cipher
Let’s write a program that encrypts text using a Caesar
Cipher! In a Caesar Cipher:

● Rotate text by n letters → this is the key (n=3 below)


● Wrap-around at the end
● Substitute letters based on this mapping

62
Exercise: Caesar Cipher
● rotate the alphabet by a certain key, with wrapping.

63
Let’s Code It!

64
Extra Practice: Recall Char Loops

// prints the characters a to z


for (char ch = 'a'; ch <= 'z'; ch++) {
println(ch);
}

65
Extra Practice: Passcodes
● So, Duke forgot his password
● It’s 3 characters long
● Each character is between a and e ?

● How can we use char loops to generate


all possible passwords for Duke to try?

aaa
aab
aac

eed
eee

66
Plan for Today

● Review: Characters and Strings


● Looping over Strings
● Practice: Reversing a String
● Practice: Palindromes
● Practice: Caesar Cipher

Next Time: How can we read data from a file?

67

You might also like