AP Computer Science Workshop


AP Classes: apstring

 
Code Effect
apstring s, t; constructs s and t as empty strings
apstring s("Hello"); constructs s from string literal "Hello"
apstring s = "Hello"; another way to construct s from "Hello"
 
apstring s = 'k'; illegal construction
apstring s = "k"; OK
 
t = s; assignment works for apstrings,
s = "Hello";    for string literals,
s = 'c';    and for single characters
 
s.length(); returns number of characters in string
 
s.find(t); returns index of first character of first occurrence of apstring t in s; npos if t does not occur in s
char ch;
s.find(ch);
returns index of first occurrence of char ch in s; npos if ch does not occur in s
int pos, len;
s.substr(pos, len);
return substring of length len starting at pos
 
cout << s[0] << endl; can index as array
s[0] = 'M'; also works on lhs of assignment operator
 
cout << s << endl; output works ...
cin >> s;    as does input
getline(istream, s); gets an entire line (and throws away '\n')
 
s += t; appends a copy of apstring t to s
s += ch; appends a copy of char ch to s
newstring = s + t; can concatenate two apstrings ...
newstring = s + ch;    as well as a string and a character ...
newstring = ch + s;    and vice versa

Previous slide Mark Stehlik, Carnegie Mellon University Next slide