Strings

783 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
783
On SlideShare
0
From Embeds
0
Number of Embeds
62
Actions
Shares
0
Downloads
26
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Strings

  1. 1. CS111 Lab Strings and classes Instructor: Michael Gordon
  2. 2. What are classes?  C++ 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  We’ve used one kind of class already: the string class  string and its functions are built into C++.
  3. 3. Strings  The 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;
  4. 4. String examples string first, last, name; cout<<"Enter your first name:"; cin>>first; cout<<"Enter your last name:"; cin>>last; cout<<"Hi, "+first+" "+last; //concat
  5. 5. getline()  cin reads the typed string only until the first whitespace.  If you want the whole string including those whitespaces, you can use:  getline(cin, stringname);  cout<<“Enter your name:”;  getline(cin, fullname);  Use fullname instead of first and last.
  6. 6. “dot” functions  With 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).
  7. 7. More functions  s1.find(string 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 index I  s1.at(int i) – returns the character at index i in string s1

×