Lecture 4/10: Strings


April 10, 2020

📂Associated files

Lecture 3: Strings

CS 106B: Programming Abstractions

Spring 2020, Stanford University Computer Science Department

Lecturers: Chris Gregg and Julie Zelenski

Reading: Programming Abstractions in C++, Chapters 3 & 4

A roll of string


Slide 2

Announcements


Slide 3

Today's Topics


Slide 4

Strings in C++

Not this type of string: A roll of string

or this one: A guitar

#include<string>
...
string s = "hello";

Slide 5

Strings and Characters

Strings are made up of characters of type char, and the characters of a string can be accessed by the index in the string (this should be familiar):

string stanfordTree = "Fear the Tree";

The Stanford Tree mascot

index: 0 1 2 3 4 5 6 7 8 9 10 11 12
character: 'F' 'e' 'a' 'r' ' ' 't' 'h' 'e' ' ' 'T' 'r' 'e' 'e'
char c1 = stanfordTree[3];    // 'r'
char c2 = stanfordTree.at(2); // 'a'
for (int i = 0; i < stanfordTree.length(); i++) {
    cout << i << " : '" << stanfordTree[i] << "'" << endl;
}
cout << endl;

for (char c : stanfordTree) {
    cout << "'" << c << "'" << endl;
}
cout << endl;

Output:

0 : 'F'
1 : 'e'
2 : 'a'
3 : 'r'
4 : ' '
5 : 't'
6 : 'h'
7 : 'e'
8 : ' '
9 : 'T'
10 : 'r'
11 : 'e'
12 : 'e'

'F'
'e'
'a'
'r'
' '
't'
'h'
'e'
' '
'T'
'r'
'e'
'e'


Slide 6

ASCII

Julius Caesar bust An ASCII table The Caesar Cipher is an encryption formed by shifting letters to the left or right in an alphabet, and re-encoding a phrase with the new letters. For a Caesar Cipher of +3, all 'A's would become 'D's, all 'B's would become 'E's, etc. At the end of the alphabet, the letters wrap, so 'X's become 'A's, 'Y's become 'B's, and 'Z's become 'C's. Julius Caesar himself is said to have used this encryption scheme to discuss battle plans with his generals, and it was (in his time) never decrypted.

Slide 7

The <cctype> library


Slide 8

String Operators


Slide 9

C++ -vs- C strings


Slide 10

C string issues


Slide 11

More C string issues


Slide 12

Mystery Function! What is the output?

The words 'Code Mystery' with a fingerprint

void mystery(string a, string &b) {
    a.erase(0,1);
    b += a[0];
    b.insert(3, "FOO");
}

int main() {
    string a = "Stanford";
    string b = "Tree";
    mystery(a,b);
    cout << a << " " << b << endl;
    return 0;
}

Answer: Stanford TreFOOet


Slide 13

The Stanford String library

#include "strlib.h"

These are not string class functions.


Slide 14

String recap


Slide 15

References and Advanced Reading