SlideShare a Scribd company logo
1 of 43
Lecture 6
             C++ Strings



                                 1
TCP1231 Computer Programming I
Objectives
 Understand the basic types of strings.
 Define and use the string class and C-type
  strings.
 Read and write strings.
 Access and manipulate characters or sub-
  strings within a string.
 Concatenate and compare strings.
 Insert, replace, swap, or erase a sub-string in
  a string.

                                              2
    TCP1231 Computer Programming I
String Taxonomy




                                 3
TCP1231 Computer Programming I
String Formats




                                 4
TCP1231 Computer Programming I
The Standard string Class
 The string class allows the programmer to
  treat strings as a basic data type
   No need to deal with the implementation as with
    C-strings
 The string class is defined in the string library
  and the names are in the standard
  namespace
   To use the string class you need these lines:
                #include <string>
            using namespace std;
                                                    5
    TCP1231 Computer Programming I
C++ String



Notes

 The extraction operator stops at whitespace.
 To read a string with spaces, we must use getline.
 The string input /output operators and functions are
  defined in the string header file, not the I/O stream
  header file

                                                    6
     TCP1231 Computer Programming I
string Constructors
 The default string constructor initializes the
  string to the empty string
 Another string constructor takes a C-string
  argument
   Example:
               string phrase;       // empty string
               string noun("ants"); // a string version
                                    // of "ants"



                                                     7
    TCP1231 Computer Programming I
#include <iostream>
#include <iomanip>
#include <string>                            Demonstrate
using namespace std;
int main ()                                  String
{
     string s1;
     string s2 ("Hello World");
                                             Constructors
     string s3 (s2);
     string s4 (5, 'A');
     string s5 (s2, 6);
     string s6 ("Hello", 2);
     string s7 ("Hello", 3, 2);              Value of s1:
                                             Value of s2: Hello World
    cout << "Value of s1: " << s1 << endl;
                                             Value of s3: Hello World
    cout << "Value of s2: " << s2 << endl;
    cout << "Value of s3: " << s3 << endl;   Value of s4: AAAAA
    cout << "Value of s4: " << s4 << endl;   Value of s5: World
    cout << "Value of s5: " << s5 << endl;   Value of s6: He
    cout << "Value of s6: " << s6 << endl;   Value of s7: lo
    cout << "Value of s7: " << s7 << endl;
    return 0;
}   // main
                                                                        8
        TCP1231 Computer Programming I
string class in C++ Standard Library
#include <iostream>
#include <string>
using namespace std;
int main() {
   char cstr[] = "Hi";
   string s1,s2;

    string   s3 = "hello";                        must #include <string> and use namespace std
    string   s4("aloha");
    string   s5 = cstr;                           construct empty string
    string   s6(cstr);
                                                  construct a string based on c-String
    string s7(s3);                                                           []
    cout << "[" <<   s1   <<   "]"   <<   endl;   construct a
    cout << "[" <<   s2   <<   "]"   <<   endl;
                                                  string based on            []
                                                  another string
    cout << "[" <<   s3   <<   "]"   <<   endl;                              [hello]
    cout << "[" <<   s4   <<   "]"   <<   endl;                              [aloha]
    cout << "[" <<   s5   <<   "]"   <<   endl;
    cout << "[" <<   s6   <<   "]"   <<   endl;
                                                                             [Hi]
    cout << "[" <<   s7   <<   "]"   <<   endl;                              [Hi]
}                                                                            [hello]
                                                                                           9
       TCP1231 Computer Programming I
Assignment of Strings
 Variables of type string can be assigned with
  the = operator
   Example:              string s1, s2, s3;
                          …
                          s3 = s2;
 Quoted strings are type cast to type string
   Example:              string s1 = "Hello Mom!";




                                                      10
    TCP1231 Computer Programming I
When assigning string to a c++ string,
#include <iostream>                      we do not need to worry about whether
#include <string>                        there is enough memory allocated or
using namespace std;
                                         not, the string will automatically adjust
int main() {                             its size if there is not enough memory
   char cstr[] = "Arnold";               allocated.
   string s1,s2,s3;
                                        assigning c-string into c++ string
    s1 = cstr;
    s2 = "Schwarzenegger";
                                        assigning a c++ string into another c++
    s3 = s1;
                                        string
    cout << "[" << s1 << "]" << endl;
    cout << "[" << s2 << "]" << endl;                  [Arnold]
    cout << "[" << s3 << "]" << endl;                  [Schwarzenegger]
}
                                                       [Arnold]


We can assign a C-strings or C++ strings directly into a C++
string without needing to use the strcpy() functions as in C-
string. The strcpy() function can only be used with C-strings.

                                                                             11
       TCP1231 Computer Programming I
#include <iostream>
#include <string>                            String
using namespace std;

int main ()
                                             Assignment
{
     string str1 ("String 1");
     string str2;
     string str3;
     string str4;
     string str5 = "String 5";

     cout << "String 1: " << str1 << endl;
     str2 = str1;
     cout << "String 2: " << str2 << endl;
     str3 = "Hello";                         String 1: String 1
     cout << "String 3: " << str3 << endl;
                                             String 2: String 1
     str4 = 'A';
     cout << "String 4: " << str4 << endl;   String 3: Hello
     cout << "String 5: " << str5 << endl;   String 4: A
     return 0;                               String 5: String 5
}    // main
                                                                  12
       TCP1231 Computer Programming I
I/O With Class string
 The insertion operator << is used to output
  objects of type string
   Example:          string s = "Hello Mom!";
                      cout << s;
 The extraction operator >> can be used to
  input data for objects of type string
   Example:       string s1;
                   cin >> s1;



                                                 13
    TCP1231 Computer Programming I
getline and Type string
 A getline function exists to read entire lines
  into a string variable
   This version of getline is not a member of the
    istream class, it is a non-member function
   Syntax for using this getline is different than that
    used with cin: cin.getline(…)
 Syntax for using getline with string objects:
    getline(Istream_Object, String_Object);


                                                     14
    TCP1231 Computer Programming I
getline Example
 This code demonstrates the use of getline with
  string objects
         string line;
          cout "Enter a line of input:n";
          getline(cin, line);
          cout << line << "END OF OUTPUTn";

      Output could be:
                         Enter some input:
                         Do be do to you!
                         Do be do to you!END OF OUTPUT

                                                   15
      TCP1231 Computer Programming I
#include <iostream>
#include <string>
                               getline
                               similar to the cin.getline() function to read
using namespace std;
int main() {
                               characters into C-string from user,
  string s;                    however, for the C++-string, the cin is one
                               of the parameter of the getline() function.
    cout << "=> ";
    cin >> s;
    cin.ignore(1000,'n');
    cout << s << endl;

    cout << "=> ";
    getline(cin, s);
                                          => how are you? i am fine
    cout << s << endl;                    how
                                          => how are you? i am fine
    cout << "=> ";
    getline(cin, s, '?');
                                          how are you? i am fine
    cout << s << endl;                    => how are you? i am fine
}                                         how are you




                                                                      16
        TCP1231 Computer Programming I
getline
#include <iostream>
#include <iomanip>
#include <string>
#include <conio.c>
using namespace std;

int main ()
{
     cout << "Enter Your Name in the form lastname,firstname: ";
     string lName;
     string fName;
     getline (cin, lName, ',');
     getline (cin, fName);

    cout << "Your Name is: " << fName << " " << lName;
         getch();
    return 0;        Enter Your Name in the form lastname,firstname:
}   // main          Azli, Fikri
                        Your Name is: Fikri Azli
                                                                       17
    TCP1231 Computer Programming I
More Examples
#include <iostream>                 #include <iostream>
#include <string>                   #include <string>
#include <conio.c>                  #include <conio.c>
using namespace std;                using namespace std;

int main ()                         int main ()
{                                   {
  cout << "Enter some words. n";     cout << "Enter some words. n";
  string strIn;                       string strIn;
  while (cin >> strIn)                while (getline(cin, strIn))
         cout << strIn << endl;              cout << strIn << endl;
  cout << “The End";                   cout << “The End";
  getch();                             getch();
  return 0;                            return 0;
}     // main                       }     // main



                                                                        18
       TCP1231 Computer Programming I
ignore
 ignore is a member of the istream class
 ignore can be used to read and discard all the

 characters, including 'n' that remain in a line
   Ignore takes two arguments
      First, the maximum number of characters to discard
      Second, the character that stops reading and
       discarding
   Example:    cin.ignore(1000, 'n');
          reads up to 1000 characters or to 'n'

                                                       19
    TCP1231 Computer Programming I
String Processing
 The string class allows the same operations
  we used with C-strings…and more
   Characters in a string object can be accessed as
    if they are in an array
     last_name[i] provides access to a single character
      as in an array
     Index values are not checked for validity!




                                                       20
    TCP1231 Computer Programming I
Member Function at
 at is an alternative to using [ ]'s to access
  characters in a string.
   at checks for valid index values
   Example:        string str("Mary");
                    cout << str[6] << endl;
                    cout << str.at(6) << endl;
                    str[2] = 'X';
                    str.at(2) = 'X';



                                                  21
     TCP1231 Computer Programming I
Member Function length

 The string class member function length
  returns
   the number of characters in the string object:

   Example:
                  int n = string_var.length( );




                                                  22
    TCP1231 Computer Programming I
Comparison of strings
 Comparison operators work with string
  objects
   Objects are compared using lexicographic order
    (Alphabetical ordering using the order of symbols
    in the ASCII character set.)
   = = returns true if two string objects contain the
    same characters in the same order
     Remember strcmp for C-strings?
   <, >, <=, >= can be used to compare string
    objects

                                                  23
    TCP1231 Computer Programming I
#include <iostream>
#include <string>
using namespace std;
                                           String
int main () {
   string str1 ("ABC Company");
   string str2 ("ABC");
                                           Comparisons
   string str3 ("ABC");

    if (str1 == str2)
         cout << "str1 == str2" << endl;

    if (str1 > str2)
        cout << "str1 > str2" << endl;

    if (str1 < str2)
        cout << "str1 < str2" << endl;

    if (str2 == str3)
                                              str1 > str2
        cout << "str2 == str3" << endl;       str2 == str3
       return 0;
}      // main                                               24
      TCP1231 Computer Programming I
Using + With strings
               (Concatenation)
 Variables of type string can be concatenated
  with the + operator
   Example:             string s1, s2, s3;
                         …
                         s3 = s1 + s2;
   If s3 is not large enough to contain s1 + s2, more
    space is allocated
 More specific, use append:
   append(string &str, size_t offset, size_t count);
   append(string &str);
   append(size_t count, char ch);

                                                    25
    TCP1231 Computer Programming I
#include <iostream>
#include <string>
using namespace std;
                                                    String
int main () {                                       Concatenation
     string str1 = "This is ";
     string str2 = "a string";           This is a string
     string str3;
                                         Begin append: This is a string
     str3 = str1 + str2;
     cout << str3 << endl;               Append method: This is a string string
                                         Append characters: This is a string!!!!!
     cout << "nBegin append: ";
     str1 = str1 + str2;                             We can add/concatenate C++
     cout << str1 << endl;                           strings, C-strings or characters
                                                     into a C++ string to form a new
     str1.append(str2, 1, string::npos);             C++ string using the '+' operator
     cout << "Append method: " << str1 << endl;      without needing to use the
                                                     strcat() functions as in C-string.
     str3.append(5, '!');                            The strcat() function can only
     cout << "Append characters: " << str3;          be used with C-strings.
     return 0;
}
                                                                               26
         TCP1231 Computer Programming I
String Extraction
 Access the substring of the calling string
  starting at position and having length
  characters
 Format
     str.substr(position, length);




                                               27
    TCP1231 Computer Programming I
#include <iostream>
#include <string>
using namespace std;                                     String
int main () {
     string str1 = "Concatenation";
                                                         Extraction
     string str2;

     cout << "str1 contains: " << str1 << endl;
     cout << "str2 contains: " << str2 << endl;
     cout << “t 0123456789012" << endl;

     str2 = str1.substr();
     cout << "str2 ==> 1: " << str2 << endl;
                                                  str1 contains: Concatenation
     str2 = str1.substr(5, 3);
     cout << "str2 ==> 2: " << str2 << endl;
                                                  str2 contains:
                                                              0123456789012
     str2 = str1.substr(5);                       str2 ==> 1: Concatenation
     cout << "str2 ==> 3: " << str2 << endl;
     return 0;
                                                  str2 ==> 2: ten
}                                                 str2 ==> 3: tenation
                                                                            28
         TCP1231 Computer Programming I
Find string
 Format
  str.find(str1);    returns index of the first occurrence of str1
                         in str
  str.find(str1, pos);
                     returns index of the first occurrence of
                     string str1 in str, the search starts at
                     position pos.
  str.find_first_of(str1, pos);
                     returns index of the first instance in str of
                         any character in str1, starting the search
    at                       position pos.
  str.find_first_not_of(str1, pos);
                     returns index of the first instance in str of
                         any character not in str1, starting the
                         search at position pos.

                                                             29
     TCP1231 Computer Programming I
#include <iostream>
#include <string>                                         Find
using namespace std;

int main ()
{
     int where;
     string str1 = "ccccatenatttt";

     where = str1.find("ten");
     cout << ""ten" at:     " << where << endl;

     where = str1.find("tin");
     if (where != string::npos)
        cout << ""tin" at:     " << where << endl;
     else
        cout << ""tin" not at:  " << where << endl;
                                                        "ten" at:        5
                                                        "tin" not at:     -1
     return 0;
}
                                                                        Page 598

                                                                          30
        TCP1231 Computer Programming I
#include <iostream>                                    Find
#include <string>
using namespace std;                    return the index of the first occurrence of string
int main() {
                                        "be" within s1 starting from position 0.
   string s1 = "...to be, or... not to
   be!";
   string s2 = "be";              return the index of the first occurrence of
   string s3;                     string "be" within s1 starting from position         8.
    s3 = s1.substr(6,13);
    cout << s3 << endl;

    cout   <<   s1.find(s2)       <<   endl;
    cout   <<   s1.find("be")     <<   endl;
    cout   <<   s1.find("be",0)   <<   endl;
    cout   <<   s1.find("be",8)   <<   endl;

    return 0;                                  be, or... not
}
                                               6
                                               6
                                               6
                                               23
                                                                                  31
       TCP1231 Computer Programming I
#include <iostream>
#include <string>
                                                   Find
using namespace std;
                                                   returns the index of the
                                                   first instance in s1 of any
int main() {                                       character in s2, starting
   string s1 = "...to be, or... not to be!";
   string s2 = "aeiou";
                                                   the search at position 11.
   string s3 = ",.!";

    cout << s1.find_first_of(s2,0) << endl;
    cout << s1.find_first_of(s2,11) << endl;

    cout << s1.find_first_not_of(s3,0) << endl;
    cout << s1.find_first_not_of(s3,12) << endl;
}
                                                         4
                                                         17
             returns the index of the first
                                                         3
             instance in s1 of any character
                                                         15
             NOT in s2, starting the search
             at position 12.


                                                                        32
       TCP1231 Computer Programming I
Insert string

 Inserts str2 into str beginning at position pos.
     str.insert(pos, str2);

 Inserts str2, beginning at position start of
  length length, into str beginning at position
  pos.
     str.insert(pos, str2, start, length);


                                               33
    TCP1231 Computer Programming I
#include <iostream>
#include <string>
using namespace std;                              Insertion
int main ()
{
     string str1 = "This is Test";
     string str2 = "tell me if, are you sure";
     cout << "str1 ==>0: " << str1 << endl;

     str1.insert(8, "a ");
     cout << "str1 ==>1: " << str1 << endl;

     str1.insert(14, str2, 10, 14);
     cout << "str1 ==>2: " << str1 << endl;

     str1 = str1.insert(str1.length(), 3, '?');
     cout << "str1 ==>3: " << str1 << endl;

     return 0;              str1 ==>0: This is Test
}                           str1 ==>1: This is a Test
                            str1 ==>2: This is a Test, are you sure
                            str1 ==>3: This is a Test, are you sure???
        TCP1231 Computer Programming I                                   34
Replace the string
 str1.replace(pos, len, str2);
      replace the str1 with str2 beginning at
        position pos of length len

 str1.replace(pos, len, str2, start, length);
      replace the str1, beginning at position pos
        of length len, with str2 beginning at
           position start of length length


                                                35
    TCP1231 Computer Programming I
#include <iostream>
#include <string>                                            Replacement
using namespace std;

int main () {
    string str1 = "My Name was Omar Ahmad";
    string str2 = "My Last Name is Zaqaibeh";

    cout << "str1 ==>0: " << str1 << endl;

    str1.replace(8, 3, "is");
    cout << "str1 ==>1: " << str1 << endl;
                                              str1 ==>0: My Name was Omar Ahmad
                                              str1 ==>1: My Name is Omar Ahmad
    str1.replace(15, 6, str2, 15, 9);
                                              str1 ==>2: My Name is Omar Zaqaibeh
    cout << "str1 ==>2: " << str1 << endl;
                                              str1 ==>3: What is Your Name?
     str1.replace(0, str1.length(), "What is Your Name?");
     cout << "str1 ==>3: " << str1 << endl;
    return 0;
}
                                                                           36
          TCP1231 Computer Programming I
#include <iostream>
#include <string>
using namespace std;                              Erase,
int main () {
     string str1 = "This is one string";
     string str3;
                                                  Clear, and
     cout << "str1 ==>0: " << str1 << endl;       Empty
     str3 = str1;
     str1.erase();
     cout << "str1 ==>1: " << str1 << endl;       str1 ==>0: This is one string
     if (str1.empty())                            str1 ==>1:
           cout <<"ntstr1 is empty nn";
     str1 = str3;
                                                       str1 is empty
     str1.erase(8, 4);
     cout << "str1 ==>2: " << str1 << endl;
     str1 = str3;                                 str1 ==>2: This is string
     str1.clear();                                str1 ==>3:
     cout << "str1 ==>3: " << str1 << endl;
     if (str1.empty())                                 str1 is empty
                 cout <<"ntstr1 is empty n";
     return 0;
}                                                                             37
         TCP1231 Computer Programming I
Swap the two strings
 swap(str1, str2);
    interchange the string str1 with str2

 Example:
   Before swapping
         str1 = “Multimedia”     str2 = “University”
   After swapping
         str1 = “University”     str2 = “Multimedia”




                                                       38
    TCP1231 Computer Programming I
#include <iostream>
#include <string>                             Swap
#include <conio.c>
using namespace std;

int main ()
{
           string str1 = "read then eat";
     string str2 = "eat then sleep";

     cout << "str1 ==>0: " << str1 << endl;
     cout << "str2 ==>0: " << str2 << endl;

     cout << endl;
     swap(str1, str2);                        str1 ==>0: read then eat
     cout << "str1 ==>1: " << str1 << endl;
                                              str2 ==>0: eat then sleep
     cout << "str2 ==>1: " << str2 << endl;
                                              str1 ==>1: eat then sleep
     return 0;
}
                                              str2 ==>1: read then eat

                                                                    39
         TCP1231 Computer Programming I
string Objects to C-strings
 Recall the automatic conversion from C-string
  to string: char a_c_string[] = "C-string";
             string_variable = a_c_string;

 strings are not converted to C-strings
 Both of these statements are illegal:
   a_c_string = string_variable;
   strcpy(a_c_string, string_variable);



                                           40
    TCP1231 Computer Programming I
Converting strings to C-strings
 The string class member function c_str
  returns the C-string version of a string object
   Example:
    strcpy(a_c_string, string_variable.c_str( ) );

 This line is still illegal
        a_c_string = string_variable.c_str( );
   Recall that operator = does not work with C-
    strings


                                                     41
    TCP1231 Computer Programming I
Conversion between C-string and C++ string
                                              valid, assign a C-string to
 char cstr[20] = "hello";
                                              C++ string
 string cppstr = "world";

 cppstr = cstr;
                                             Invalid, can not assign nor
 cstr = cppstr;                              copy a C++-string to C
 strcpy(cstr, cppstr);                       string.

 strcpy(cstr, cppstr.c_str() );
                                           valid, convert a C++-string to C
                                           string (using the c_str()
 cstr = cppstr.c_str() ;                   function) before it is being copy
                                           into the C-string

Invalid, even though the C++-string has been convert to C-string, we can
not assign the new C-string into another C-string, we need to use the
strcpy() for that.


                                                                      42
     TCP1231 Computer Programming I
The End




                                 43
TCP1231 Computer Programming I

More Related Content

What's hot

What's hot (20)

Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
Pointers
PointersPointers
Pointers
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2
 
C++11
C++11C++11
C++11
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
 
C++ Chapter I
C++ Chapter IC++ Chapter I
C++ Chapter I
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 

Similar to Computer Programming- Lecture 6

Similar to Computer Programming- Lecture 6 (20)

lecture-5 string.pptx
lecture-5 string.pptxlecture-5 string.pptx
lecture-5 string.pptx
 
C++ Strings.ppt
C++ Strings.pptC++ Strings.ppt
C++ Strings.ppt
 
Array and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxArray and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptx
 
String in c programming
String in c programmingString in c programming
String in c programming
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
strings
stringsstrings
strings
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
Project in programming
Project in programmingProject in programming
Project in programming
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Savitch Ch 08
Savitch Ch 08Savitch Ch 08
Savitch Ch 08
 
C chap08
C chap08C chap08
C chap08
 
Strings
StringsStrings
Strings
 
Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++
 
Programming - Marla Fuentes
Programming - Marla FuentesProgramming - Marla Fuentes
Programming - Marla Fuentes
 
Savitch ch 08
Savitch ch 08Savitch ch 08
Savitch ch 08
 
C++ practical
C++ practicalC++ practical
C++ practical
 
Lecture 3: Strings and Dynamic Memory Allocation
Lecture 3: Strings and Dynamic Memory AllocationLecture 3: Strings and Dynamic Memory Allocation
Lecture 3: Strings and Dynamic Memory Allocation
 
Oop1
Oop1Oop1
Oop1
 

Recently uploaded

HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 

Recently uploaded (20)

HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 

Computer Programming- Lecture 6

  • 1. Lecture 6 C++ Strings 1 TCP1231 Computer Programming I
  • 2. Objectives  Understand the basic types of strings.  Define and use the string class and C-type strings.  Read and write strings.  Access and manipulate characters or sub- strings within a string.  Concatenate and compare strings.  Insert, replace, swap, or erase a sub-string in a string. 2 TCP1231 Computer Programming I
  • 3. String Taxonomy 3 TCP1231 Computer Programming I
  • 4. String Formats 4 TCP1231 Computer Programming I
  • 5. The Standard string Class  The string class allows the programmer to treat strings as a basic data type  No need to deal with the implementation as with C-strings  The string class is defined in the string library and the names are in the standard namespace  To use the string class you need these lines: #include <string> using namespace std; 5 TCP1231 Computer Programming I
  • 6. C++ String Notes  The extraction operator stops at whitespace.  To read a string with spaces, we must use getline.  The string input /output operators and functions are defined in the string header file, not the I/O stream header file 6 TCP1231 Computer Programming I
  • 7. string Constructors  The default string constructor initializes the string to the empty string  Another string constructor takes a C-string argument  Example: string phrase; // empty string string noun("ants"); // a string version // of "ants" 7 TCP1231 Computer Programming I
  • 8. #include <iostream> #include <iomanip> #include <string> Demonstrate using namespace std; int main () String { string s1; string s2 ("Hello World"); Constructors string s3 (s2); string s4 (5, 'A'); string s5 (s2, 6); string s6 ("Hello", 2); string s7 ("Hello", 3, 2); Value of s1: Value of s2: Hello World cout << "Value of s1: " << s1 << endl; Value of s3: Hello World cout << "Value of s2: " << s2 << endl; cout << "Value of s3: " << s3 << endl; Value of s4: AAAAA cout << "Value of s4: " << s4 << endl; Value of s5: World cout << "Value of s5: " << s5 << endl; Value of s6: He cout << "Value of s6: " << s6 << endl; Value of s7: lo cout << "Value of s7: " << s7 << endl; return 0; } // main 8 TCP1231 Computer Programming I
  • 9. string class in C++ Standard Library #include <iostream> #include <string> using namespace std; int main() { char cstr[] = "Hi"; string s1,s2; string s3 = "hello"; must #include <string> and use namespace std string s4("aloha"); string s5 = cstr; construct empty string string s6(cstr); construct a string based on c-String string s7(s3); [] cout << "[" << s1 << "]" << endl; construct a cout << "[" << s2 << "]" << endl; string based on [] another string cout << "[" << s3 << "]" << endl; [hello] cout << "[" << s4 << "]" << endl; [aloha] cout << "[" << s5 << "]" << endl; cout << "[" << s6 << "]" << endl; [Hi] cout << "[" << s7 << "]" << endl; [Hi] } [hello] 9 TCP1231 Computer Programming I
  • 10. Assignment of Strings  Variables of type string can be assigned with the = operator  Example: string s1, s2, s3; … s3 = s2;  Quoted strings are type cast to type string  Example: string s1 = "Hello Mom!"; 10 TCP1231 Computer Programming I
  • 11. When assigning string to a c++ string, #include <iostream> we do not need to worry about whether #include <string> there is enough memory allocated or using namespace std; not, the string will automatically adjust int main() { its size if there is not enough memory char cstr[] = "Arnold"; allocated. string s1,s2,s3; assigning c-string into c++ string s1 = cstr; s2 = "Schwarzenegger"; assigning a c++ string into another c++ s3 = s1; string cout << "[" << s1 << "]" << endl; cout << "[" << s2 << "]" << endl; [Arnold] cout << "[" << s3 << "]" << endl; [Schwarzenegger] } [Arnold] We can assign a C-strings or C++ strings directly into a C++ string without needing to use the strcpy() functions as in C- string. The strcpy() function can only be used with C-strings. 11 TCP1231 Computer Programming I
  • 12. #include <iostream> #include <string> String using namespace std; int main () Assignment { string str1 ("String 1"); string str2; string str3; string str4; string str5 = "String 5"; cout << "String 1: " << str1 << endl; str2 = str1; cout << "String 2: " << str2 << endl; str3 = "Hello"; String 1: String 1 cout << "String 3: " << str3 << endl; String 2: String 1 str4 = 'A'; cout << "String 4: " << str4 << endl; String 3: Hello cout << "String 5: " << str5 << endl; String 4: A return 0; String 5: String 5 } // main 12 TCP1231 Computer Programming I
  • 13. I/O With Class string  The insertion operator << is used to output objects of type string  Example: string s = "Hello Mom!"; cout << s;  The extraction operator >> can be used to input data for objects of type string  Example: string s1; cin >> s1; 13 TCP1231 Computer Programming I
  • 14. getline and Type string  A getline function exists to read entire lines into a string variable  This version of getline is not a member of the istream class, it is a non-member function  Syntax for using this getline is different than that used with cin: cin.getline(…)  Syntax for using getline with string objects: getline(Istream_Object, String_Object); 14 TCP1231 Computer Programming I
  • 15. getline Example  This code demonstrates the use of getline with string objects  string line; cout "Enter a line of input:n"; getline(cin, line); cout << line << "END OF OUTPUTn"; Output could be: Enter some input: Do be do to you! Do be do to you!END OF OUTPUT 15 TCP1231 Computer Programming I
  • 16. #include <iostream> #include <string> getline similar to the cin.getline() function to read using namespace std; int main() { characters into C-string from user, string s; however, for the C++-string, the cin is one of the parameter of the getline() function. cout << "=> "; cin >> s; cin.ignore(1000,'n'); cout << s << endl; cout << "=> "; getline(cin, s); => how are you? i am fine cout << s << endl; how => how are you? i am fine cout << "=> "; getline(cin, s, '?'); how are you? i am fine cout << s << endl; => how are you? i am fine } how are you 16 TCP1231 Computer Programming I
  • 17. getline #include <iostream> #include <iomanip> #include <string> #include <conio.c> using namespace std; int main () { cout << "Enter Your Name in the form lastname,firstname: "; string lName; string fName; getline (cin, lName, ','); getline (cin, fName); cout << "Your Name is: " << fName << " " << lName; getch(); return 0; Enter Your Name in the form lastname,firstname: } // main Azli, Fikri Your Name is: Fikri Azli 17 TCP1231 Computer Programming I
  • 18. More Examples #include <iostream> #include <iostream> #include <string> #include <string> #include <conio.c> #include <conio.c> using namespace std; using namespace std; int main () int main () { { cout << "Enter some words. n"; cout << "Enter some words. n"; string strIn; string strIn; while (cin >> strIn) while (getline(cin, strIn)) cout << strIn << endl; cout << strIn << endl; cout << “The End"; cout << “The End"; getch(); getch(); return 0; return 0; } // main } // main 18 TCP1231 Computer Programming I
  • 19. ignore  ignore is a member of the istream class  ignore can be used to read and discard all the characters, including 'n' that remain in a line  Ignore takes two arguments  First, the maximum number of characters to discard  Second, the character that stops reading and discarding  Example: cin.ignore(1000, 'n'); reads up to 1000 characters or to 'n' 19 TCP1231 Computer Programming I
  • 20. String Processing  The string class allows the same operations we used with C-strings…and more  Characters in a string object can be accessed as if they are in an array  last_name[i] provides access to a single character as in an array  Index values are not checked for validity! 20 TCP1231 Computer Programming I
  • 21. Member Function at  at is an alternative to using [ ]'s to access characters in a string.  at checks for valid index values  Example: string str("Mary"); cout << str[6] << endl; cout << str.at(6) << endl; str[2] = 'X'; str.at(2) = 'X'; 21 TCP1231 Computer Programming I
  • 22. Member Function length  The string class member function length returns the number of characters in the string object:  Example: int n = string_var.length( ); 22 TCP1231 Computer Programming I
  • 23. Comparison of strings  Comparison operators work with string objects  Objects are compared using lexicographic order (Alphabetical ordering using the order of symbols in the ASCII character set.)  = = returns true if two string objects contain the same characters in the same order  Remember strcmp for C-strings?  <, >, <=, >= can be used to compare string objects 23 TCP1231 Computer Programming I
  • 24. #include <iostream> #include <string> using namespace std; String int main () { string str1 ("ABC Company"); string str2 ("ABC"); Comparisons string str3 ("ABC"); if (str1 == str2) cout << "str1 == str2" << endl; if (str1 > str2) cout << "str1 > str2" << endl; if (str1 < str2) cout << "str1 < str2" << endl; if (str2 == str3) str1 > str2 cout << "str2 == str3" << endl; str2 == str3 return 0; } // main 24 TCP1231 Computer Programming I
  • 25. Using + With strings (Concatenation)  Variables of type string can be concatenated with the + operator  Example: string s1, s2, s3; … s3 = s1 + s2;  If s3 is not large enough to contain s1 + s2, more space is allocated  More specific, use append:  append(string &str, size_t offset, size_t count);  append(string &str);  append(size_t count, char ch); 25 TCP1231 Computer Programming I
  • 26. #include <iostream> #include <string> using namespace std; String int main () { Concatenation string str1 = "This is "; string str2 = "a string"; This is a string string str3; Begin append: This is a string str3 = str1 + str2; cout << str3 << endl; Append method: This is a string string Append characters: This is a string!!!!! cout << "nBegin append: "; str1 = str1 + str2; We can add/concatenate C++ cout << str1 << endl; strings, C-strings or characters into a C++ string to form a new str1.append(str2, 1, string::npos); C++ string using the '+' operator cout << "Append method: " << str1 << endl; without needing to use the strcat() functions as in C-string. str3.append(5, '!'); The strcat() function can only cout << "Append characters: " << str3; be used with C-strings. return 0; } 26 TCP1231 Computer Programming I
  • 27. String Extraction  Access the substring of the calling string starting at position and having length characters  Format str.substr(position, length); 27 TCP1231 Computer Programming I
  • 28. #include <iostream> #include <string> using namespace std; String int main () { string str1 = "Concatenation"; Extraction string str2; cout << "str1 contains: " << str1 << endl; cout << "str2 contains: " << str2 << endl; cout << “t 0123456789012" << endl; str2 = str1.substr(); cout << "str2 ==> 1: " << str2 << endl; str1 contains: Concatenation str2 = str1.substr(5, 3); cout << "str2 ==> 2: " << str2 << endl; str2 contains: 0123456789012 str2 = str1.substr(5); str2 ==> 1: Concatenation cout << "str2 ==> 3: " << str2 << endl; return 0; str2 ==> 2: ten } str2 ==> 3: tenation 28 TCP1231 Computer Programming I
  • 29. Find string  Format str.find(str1); returns index of the first occurrence of str1 in str str.find(str1, pos); returns index of the first occurrence of string str1 in str, the search starts at position pos. str.find_first_of(str1, pos); returns index of the first instance in str of any character in str1, starting the search at position pos. str.find_first_not_of(str1, pos); returns index of the first instance in str of any character not in str1, starting the search at position pos. 29 TCP1231 Computer Programming I
  • 30. #include <iostream> #include <string> Find using namespace std; int main () { int where; string str1 = "ccccatenatttt"; where = str1.find("ten"); cout << ""ten" at: " << where << endl; where = str1.find("tin"); if (where != string::npos) cout << ""tin" at: " << where << endl; else cout << ""tin" not at: " << where << endl; "ten" at: 5 "tin" not at: -1 return 0; } Page 598 30 TCP1231 Computer Programming I
  • 31. #include <iostream> Find #include <string> using namespace std; return the index of the first occurrence of string int main() { "be" within s1 starting from position 0. string s1 = "...to be, or... not to be!"; string s2 = "be"; return the index of the first occurrence of string s3; string "be" within s1 starting from position 8. s3 = s1.substr(6,13); cout << s3 << endl; cout << s1.find(s2) << endl; cout << s1.find("be") << endl; cout << s1.find("be",0) << endl; cout << s1.find("be",8) << endl; return 0; be, or... not } 6 6 6 23 31 TCP1231 Computer Programming I
  • 32. #include <iostream> #include <string> Find using namespace std; returns the index of the first instance in s1 of any int main() { character in s2, starting string s1 = "...to be, or... not to be!"; string s2 = "aeiou"; the search at position 11. string s3 = ",.!"; cout << s1.find_first_of(s2,0) << endl; cout << s1.find_first_of(s2,11) << endl; cout << s1.find_first_not_of(s3,0) << endl; cout << s1.find_first_not_of(s3,12) << endl; } 4 17 returns the index of the first 3 instance in s1 of any character 15 NOT in s2, starting the search at position 12. 32 TCP1231 Computer Programming I
  • 33. Insert string  Inserts str2 into str beginning at position pos. str.insert(pos, str2);  Inserts str2, beginning at position start of length length, into str beginning at position pos. str.insert(pos, str2, start, length); 33 TCP1231 Computer Programming I
  • 34. #include <iostream> #include <string> using namespace std; Insertion int main () { string str1 = "This is Test"; string str2 = "tell me if, are you sure"; cout << "str1 ==>0: " << str1 << endl; str1.insert(8, "a "); cout << "str1 ==>1: " << str1 << endl; str1.insert(14, str2, 10, 14); cout << "str1 ==>2: " << str1 << endl; str1 = str1.insert(str1.length(), 3, '?'); cout << "str1 ==>3: " << str1 << endl; return 0; str1 ==>0: This is Test } str1 ==>1: This is a Test str1 ==>2: This is a Test, are you sure str1 ==>3: This is a Test, are you sure??? TCP1231 Computer Programming I 34
  • 35. Replace the string  str1.replace(pos, len, str2); replace the str1 with str2 beginning at position pos of length len  str1.replace(pos, len, str2, start, length); replace the str1, beginning at position pos of length len, with str2 beginning at position start of length length 35 TCP1231 Computer Programming I
  • 36. #include <iostream> #include <string> Replacement using namespace std; int main () { string str1 = "My Name was Omar Ahmad"; string str2 = "My Last Name is Zaqaibeh"; cout << "str1 ==>0: " << str1 << endl; str1.replace(8, 3, "is"); cout << "str1 ==>1: " << str1 << endl; str1 ==>0: My Name was Omar Ahmad str1 ==>1: My Name is Omar Ahmad str1.replace(15, 6, str2, 15, 9); str1 ==>2: My Name is Omar Zaqaibeh cout << "str1 ==>2: " << str1 << endl; str1 ==>3: What is Your Name? str1.replace(0, str1.length(), "What is Your Name?"); cout << "str1 ==>3: " << str1 << endl; return 0; } 36 TCP1231 Computer Programming I
  • 37. #include <iostream> #include <string> using namespace std; Erase, int main () { string str1 = "This is one string"; string str3; Clear, and cout << "str1 ==>0: " << str1 << endl; Empty str3 = str1; str1.erase(); cout << "str1 ==>1: " << str1 << endl; str1 ==>0: This is one string if (str1.empty()) str1 ==>1: cout <<"ntstr1 is empty nn"; str1 = str3; str1 is empty str1.erase(8, 4); cout << "str1 ==>2: " << str1 << endl; str1 = str3; str1 ==>2: This is string str1.clear(); str1 ==>3: cout << "str1 ==>3: " << str1 << endl; if (str1.empty()) str1 is empty cout <<"ntstr1 is empty n"; return 0; } 37 TCP1231 Computer Programming I
  • 38. Swap the two strings  swap(str1, str2); interchange the string str1 with str2  Example:  Before swapping str1 = “Multimedia” str2 = “University”  After swapping str1 = “University” str2 = “Multimedia” 38 TCP1231 Computer Programming I
  • 39. #include <iostream> #include <string> Swap #include <conio.c> using namespace std; int main () { string str1 = "read then eat"; string str2 = "eat then sleep"; cout << "str1 ==>0: " << str1 << endl; cout << "str2 ==>0: " << str2 << endl; cout << endl; swap(str1, str2); str1 ==>0: read then eat cout << "str1 ==>1: " << str1 << endl; str2 ==>0: eat then sleep cout << "str2 ==>1: " << str2 << endl; str1 ==>1: eat then sleep return 0; } str2 ==>1: read then eat 39 TCP1231 Computer Programming I
  • 40. string Objects to C-strings  Recall the automatic conversion from C-string to string: char a_c_string[] = "C-string"; string_variable = a_c_string;  strings are not converted to C-strings  Both of these statements are illegal:  a_c_string = string_variable;  strcpy(a_c_string, string_variable); 40 TCP1231 Computer Programming I
  • 41. Converting strings to C-strings  The string class member function c_str returns the C-string version of a string object  Example: strcpy(a_c_string, string_variable.c_str( ) );  This line is still illegal a_c_string = string_variable.c_str( );  Recall that operator = does not work with C- strings 41 TCP1231 Computer Programming I
  • 42. Conversion between C-string and C++ string valid, assign a C-string to char cstr[20] = "hello"; C++ string string cppstr = "world"; cppstr = cstr; Invalid, can not assign nor cstr = cppstr; copy a C++-string to C strcpy(cstr, cppstr); string. strcpy(cstr, cppstr.c_str() ); valid, convert a C++-string to C string (using the c_str() cstr = cppstr.c_str() ; function) before it is being copy into the C-string Invalid, even though the C++-string has been convert to C-string, we can not assign the new C-string into another C-string, we need to use the strcpy() for that. 42 TCP1231 Computer Programming I
  • 43. The End 43 TCP1231 Computer Programming I