On completion of chapter 13 students will know how to: Create strings with the C++ string class, manipulate strings with string functions, read a word, or multiple lines from keyboard, use the string class in programs.
Trang 1Chapter 13 – C++ String Class
Trang 2Do not need to specify size of string object
– C++ keeps track of size of text
– C++ expands memory region to store text as needed
Can use operators to perform some string manipulations
Lesson 13.1
Trang 3Declaring string Objects
Use the class name string and list object names
Trang 4s1 = "This is an example.";
Trang 6C Strings vs. string Objects
Older code uses C strings
C strings more basic – faster execution
String class improves ability to manipulate text safely
– Sized automatically
– No null necessary
– Easier modification in program
Lesson 13.1
Trang 7– Invoking object
One that is modified Lesson 13.2
Trang 9Overloaded find Function
Another version has two arguments
Basic form: ob1.find (ob2, index);
– index represents integer value for beginning of search
C++ performs automatic type conversion from C strings to string objects when C
strings are in string function call
String not found returns 1
Lesson 13.2
Trang 10Replaces characters within a string object with another string
Trang 11Eliminates characters within string objectBasic form: ob1.erase (index, num);
– num represents number of characters to erase – index is the beginning position
Returns reference to the invoking object
Lesson 13.2
s1 = "This is an example.";
s1.erase (8,3);example.";
Trang 14Lesson 13.3
Trang 15Lesson 13.3
Trang 18Lesson 13.5
class Class1 {
Trang 19<< endl;
getline (cin ,s1);
cout<< "Enter phone number." <<endl;
cin.getline (aa) }
return s1;
}
Trang 21Create strings with the C++ string classManipulate strings with string functionsRead a word, or multiple lines from
keyboard
Use the string class in programs
Learned how to: