Tải bản đầy đủ (.pdf) (21 trang)

Lecture Programming in C++ - Chapter 13: C++ string class

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (406.28 KB, 21 trang )

Chapter 13 – C++ String Class


String objects
Do 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


Declaring string Objects
Use the class name string and list object 
names
Example:        string  s1, s2, s3;
– s1, s2, s3  would be string objects

String header needed to declare string 
objects
Do NOT specify size (Note: no brackets)


Initializing string Objects
Can initialize with the =
– C++ automatically reserves sufficient memory

s1 = "This is an example.";


Can also place in ( ) but still need " "
Null character not required for string text
Data member of string class stores size of 
text
Lesson 13.1


Operators + string Objects
Type       Operator
Assignment =
+=
Comparison ==
!=
 >
 <
>=
<=
Input/Output >>
<<
Character
[ ]
      access
Concatenation  +
Lesson 13.1

Action
Stores string
Concatenates and stores
True if strings identical
True if strings not identical

True if first string greater than second
True if first string is less than second
True if first string greater or equal than second
True if first string less or equal than second
For input and string objects
For output and string objects
To access individual characters 
Connects two strings


C 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


Some Member Functions
More actions needed than operators can 
provide
Calling member function involves using 
object name with dot operator and function 
name
– Invoking object
One that is modified


Lesson 13.2


find Function
Searches for a string within a string
Basic form of call to find
              ob1.find (ob2);
– finds first occurrence of string ob2 within ob1

Returns position

0  1 2 3 4  5 6 7 8 9 0  1

s1 = "This is an example.";
s2 = "exam";
The return value is 11
n = s1.find (s2);
Lesson 13.2


Overloaded 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


replace Function
Replaces characters within a string object with 
another string
Returns reference to invoking object
Basic form:  ob1.replace (index, num, ob2);
– index represents position to begin
– num is the number of characters to replace
– ob2 what is to be used to replace (can be C string)
portion of ob2 to use
Overloaded:  
   ob1.replace (index1, num1, ob2, index2, num2);
Lesson 13.2


erase Function
Eliminates characters within string object
Basic form:   ob1.erase (index, num);
– num represents number of characters to erase
– index is the beginning position

Returns reference to the invoking object
s1 = "This is an example.";
example.";      
s1.erase (8,3);
Lesson 13.2



insert Function
Adds characters to a string object
Basic form:     ob1.insert (index, ob2);
– index is beginning position
– ob2 represents what is to be inserted
Can be a C string

Returns reference to the invoking function
s1 = "This is an example.";
just an example.";
s1.insert (8,"just ");
Lesson 13.2


Other string Functions
Many other functions available
– Examples:  compare, append, resize, etc.

Described in text, table 13.2





List of functions
Sample syntax
What they return
Description of purpose

Lesson 13.2



Reading a Single Word
From keyboard using cin
            cin >> s1;
– Reads characters until whitespace typed 
– Whitespace includes space and "Enter" key

Amount of memory for s1 automatically 
made sufficient

Lesson 13.3


Reading Multiple Lines
Use function getline
– Contained in <string>

General form:  getline (cin, ob1, 'terminator');
– Ob1 is name of string object
– Terminator is terminating character
Read but not included in ob1 object
Default value is '\n'

Read single line of input:  getline (cin, ob1);
Lesson 13.3


Reading an Input File
Use getline for complete file

– Read each line into 1­D array of string objects

Use for loop
General form:
       for ( int j = 0; j < num_lines; j++)
             {
              getline (infile, array_element);
              }
Lesson 13.3


Strings and Functions
string  function1 (string, const string[ ], string&, string [ ]);

Return type for function is string object
string objects passed like other objects
– Copy is passed when type string is argument

Keyword const prevents array elements 
from being modified
& indicates a reference
Lesson 13.4


Class Definition: Example
class Class1
         {
Both C strings           private:
and string objects                     char  aa [20];
can be members                      string s1;

         public:
of a class
                    char* get_aa( );
"get" functions return
                    string get_s1 ( );
Function reads both
private data member
                    void  read_data ( );
data members
          };
Lesson 13.5


Member Functions
class Class1
         {
         private:
                    char  aa [20];
                    string s1;
         public:
                    char* get_aa( );
                    string get_s1 ( );
                    void  read_data ( );
          };

char* Class1 :: get_aa ( )
         {
          return aa;
          }
Lesson 13.5


void Class1 :: read_data ( )
       {
       cout << "Enter your name."
               <<  endl;
       getline (cin ,s1);
       cout<< "Enter phone number."
              <       cin.getline (aa)
       }
string Class1 :: get_s1 ( )
         {
          return s1;
          }


Working With a Class
Object of class declared – allows member 
functions to be called
Example:  
Class1 ob1;
ob1.read_data ( );
cout <
Lesson 13.5


Summary
Learned 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



×