Lab # 11

© Manzur Ashraf

Objective:

Learn how to use Strings.

 

Scope:

The student should know the following:

       1.         Read and Print Strings

      2.         Use the built-in string functions

 

What is String ?

 

A string is any sequence of characters enclosed in double quotes. There is no separate data type for strings as integer, float or double. The string data type can be considered as a char array. The difference is that a character variable can hold only one character but a string can have more than one character in a character array. For example, a string called name with 9 characters can be declared as:

 

                                                char   name [9] = “I like C” ;

 

Check for the double quotes, the char array size 9. Here the name can be considered as one string or as an array of characters. That is if you refer name it is “I like C” and if you refer name[0] it is ‘I’, name[1] is   ‘ ‘ (a blank), name[2] is ‘l’, name[3] is ‘i’, and so on. The last character name[8] is ‘\0’ which indicates a NULL character which is not displayed but is stored as last character of the string to indicate its end.

Note: Strings are stored as arrays of characters and have a special ‘\0’ termination character called NULL appended (attached) to them to signify the end of the string.

 

Note that if the number of characters including the ‘\0’ is more than the size of the array the results will be unpredictable. However, if the size of the array is more than the number of characters the extra spaces after the last ‘\0’ character are kept blank and not referred because the string ends at ‘\0’. So, always make sure that the size of the array is sufficient for the string.  For example, the above declaration would be wrong if we write

                                                char   name [8] = “I like C” ;

 

The size can be ignored also. In that case the size is considered as that of the number of characters specified in the declaration.

                                                char   name [ ] = “I like C” ;

 

String Input/Output:

 

The easiest way to input strings is by using the C library function gets (means get string). The gets( ) function reads a string of characters entered at the keyboard until you strike the enter key (carriage return). The carriage return does not become part of the string; instead a null terminator ‘\0’ is placed at the end.

For example, in the following program fragment

                                    char   str[80] ;

 

                                    gets (str) ;

and if the user enters

                                    Rafiqul Zaman Khan

 

and presses the enter key the string variable str has the characters “Rafiqul Zaman Khan” with ‘\0’ appended at the end but is not displayed.

Similarly, there is an output function puts ( ) which prints or displays the value of the string variable. Unlike the printf, which stays on the same line after printing puts automatically advances the output to the next line after displaying it.

                                    puts (str) ;

 

Example:                       char   name [81] = {“Rafiqul Zaman Khan”} ;

                        gets (name) ;  /* reads the name */

                        puts (name) ;  /* prints the name */

 

You can also use the scanf function for string input by means of the %s format specifier and the printf function for string output. But the disadvantage with it is that scanf interprets a blank as the end of the particular input value. As a result you can’t read the above line    Rafiqul Zaman Khan   with scanf using a single string variable. You need to take 3 string variables to read the 3 words as

 

                                    char   first[10], second[10], third[10] ;

 

                                    scanf (“%s %s %s”, first, second, third) ;

                        printf (“My name is : %s %s %s\n”, first, second, last ) ;

 

Note that there is no & (address of) operator for string variables when they are read with scanf.

 

Built-in String Functions:

 

A large collection of string processing functions are provided in C through string.h file. So, include the string.h file in the programs to use these functions. To use the string functions make sure that the size of the array is sufficient so that the strings are terminated with the ‘\0’ character or the functions will not work properly.

 

strcat ( string1, string2 ) :

 

            The strcat function concatenates or joins the string1 and string2. A copy of string2 is put at the end of the string1. Make sure that string1 size is long enough to hold the resulting string (string1 + string2).

Example:           char   string1[ 81] = “abc”,  string2 [ ] = “def” ;

 

                        strcat ( string1, string2) ;

                puts ( string1 ) ;                                 /* outputs “abcdef” which is stored in string1 */

 

 

strcpy ( string1, string2 ) :

 

            The strcpy function copies string2 into string1. Again make sure that string1 size is long enough to hold the resulting string.

Example:       char   string1 [ 81] ,   string2 [ ] = “memory” ;

 

                strcpy ( string1, string2 ) ;

                Puts ( string1 ) ;                                 /* outputs “memory” copied into string1 */

 

 

strcmp ( string1, string2 ) :

 

            The strcmp function compares the string1 to string2 and returns an integer value to show the status of the comparison. A value of 0 indicates that the two strings are identical. A value of less than 0 shows that string1 is lexicographically (according to alphabetic ordering) less than string2. A value of greater than 0 shows that string1 is lexicographically (according to alphabetic ordering) greater than string2.

Example:           char   string1 [ ] = “John Doe” ;

                char   string2 [ ] = “John Doe” ;

                char   string3 [ ] = “Jane Doe” ;

                char   string4 [ ] = “John Does” ;

 

                printf ( “%d %d %d”, strcmp (string1, string2), strcmp (string1, string3),

       strcmp (string1, string4) ) ;   /* outputs 0, >0, <0 */

 

Note that when the strings are not equal the result is positive or negative and not the exact value.

 

strlen ( string1 ) :

 

            The strlen function returns an integer equal to the length of the stored string including blanks, not including the termination character.

Example:           char   string1 [81] ;

                char   string2 [ ] = “Jane Doe” ;

 

     printf (“%d %d”, strlen ( string1 ), strlen ( string2 ) ) ;   /* outputs 0 for string1, 8 for string2 */

 

 

strchr ( string, ch ) :

 

            The strchr function searches string for the first occurrence of ch. This function only tells whether the string contains ch or not and it will not tell the position of the ch in the string if found.

Example:           char   string [9] = “John Doe” ;

                char   search = ‘D’ ;

 

                if ( strchr (string, search ) != NULL )

                        printf (“Search character found\n”) ;   /* outputs this message */

                        else

                        printf (“Search character not found\n”) ;

 

Arrays of strings:

 

To represent arrays of strings we need two-dimensional arrays. The first-dimension represents the number of strings in the array and the second-dimension represents the length of each string.

Example:          #define        LEN1 5

                #define   LEN2       81    

char   strarray [ LEN1 ] [ LEN2 ] = {“This”, “is”, “ICS201”, “Course”, “LAB”} ;

char   str [LEN2] = {“Instructor”} ;

 

Here the array strarray is an array of 5 strings with the size of each string being 81. Thus

 

                      strarray [0] [0] = ‘T’, strarray [0] [1] = ‘h’, strarray [0] [2] = ‘i’,

                  strarray [0] [3] = ‘s’, strarray[0][4] = ‘\0’;

Similarly,         strarray [4] [0] = ‘L’, strarray [4] [1] = ‘A’, strarray [4] [2] = ‘B’, strarray[4][3] = ‘\0’.

 

The string arrays can be read by using gets ( ) and printed by using puts ( ) inside a for loop as

 

                        #define         LEN1 5

                #define   LEN2       81    

char   strarray [ LEN1 ] [ LEN2 ] ;

int     i ;

 

for ( i = 0 ; i < 5 ; ++i )

{       printf (“Enter the %d string\n”, i ) ;

        gets ( strarray [ i ] ) ;

        puts ( strarray [ i ] ) ;

                }

                       

 

 

Programming Exercise

 

                       

Program # 1    Write a program that initializes a character array first of size 20 , character array last of size 20 and array full of character of size 40 . Array first contains the first name , array last contains the last name, array full joins the two strings together  first and last . 

 

Program # 2    Write a program that uses 5 strings str1, str2, str3, str4, str5 each of size 81.

Let str1=“what”, str2 = “whatsoever, str3 = “ever”, str4 = “whatever”.

Then it should do the following:

 

            Join the str3 to str1 and print the str1.

            Copy the str1 to the str5 and print str5.

            Compare the str5 and str4 and print whether they are equal or not.

            Find the lengths of the string str1 and print.

            Check whether the character ‘w’ occurs in both the strings str2 and str3 and prints “yes” if it  

            occurs.

                       

Use puts ( ) function for printing strings.