Page 300 - Computer_Science_F5
P. 300

Output: The length of string1 will be as shown in Figure 4.69.






          FOR ONLINE READING ONLY
                                   Figure 4.69: Output of string length function                   Chapter Four: Object oriented programming with C++


              strcmp( )
              The following Program Example  4.39 shows the use of the string function  that
              compares the two string values and returns 0 if the two strings are the same; returns
              -1 if the value of string1<string2, and 1 when string1>string2.

              This function is used in a scenario where you are required to enter your name and
              password to login to a particular website. In such cases, at the administrator side , it
              is needed to build and script functions that will check and compare the input string
              (login details) with the string stored in the data base of the site.

                      Program Example 4.39:

               Using strcmp( ) string function
               Taking the string s1 and s2 in strcmp(s1, s2), this string function of C++ will
               compare the string s1 and s2 and return 0, -1 or 1

                           #include <iostream>
                            #include <cstring>
                            using namespace std;
                            int main()
                            {
                            char string1[]=”Hujambo”;
                            char string2[]=”Mwananzengo”;
                            cout << “The result of strcmp is : “ <<strcmp(string1, string2) <<
                           ‘\n’;
                            }

               Output:  The result will be -1 as shown in Figure 4.70. Find the result when you
                         put char string1[]= “Mwananzengo” and char string2[]= “Hujambo”,
                         and when you put char string1[]= “Mwananzengo” and char string2[]=
                         “Mwananzengo”.









                                   Figure 4.70: Output of string compare function

                                                    291
               Student’s Book  Form Five



     Computer Science Form 5.indd   291                                                     23/07/2024   12:34
   295   296   297   298   299   300   301   302   303   304   305