Strings and classes
Instructor: Michael Gordon
What are classes?
was originally called “C with classes”
A class can be thought of as new type of
variable that you can create.
Just like functions are new operations you
can write, classes are new variables
used one kind of class already: the
string and its functions are built into C++.
internal construction of a string is
really an array of characters.
To find the length of a string s we can use
the functions .length() or .size
int x = s.length(); gives x the value of the
size of the string s.
To “concatenate” two strings s1 and s2:
string s3 = s1+s2;
string first, last, name;
cout<<"Enter your first name:";
cout<<"Enter your last name:";
cout<<"Hi, "+first+" "+last; //concat
reads the typed string only until the first
If you want the whole string including
those whitespaces, you can use:
Use fullname instead of first and last.
strings we start dealing with a new
kind of function call. These functions
operate on a specific “object” (an
instance of a class).
We write the object name (e.g. the
variable name of the string) followed by
period and the function call (no space
before or after the period).
s2) – returns the index of the
beginning of s2 in s1.
s1 = “hello”;
s1.find(“lo”) – returns 3
s1.insert(int i, string s2) – inserts s2 into s1 at
s1.at(int i) – returns the character at index
i in string s1