Sorting of strings in alphabetical order

Program 37) Write a program that would sort a list of names in alphabetical order.


A program to sort the list of strings in alphabetical order. It employs the method of bubble sorting.

                                   PROGRAM

#define ITEMS 5
#define MAXCHAR 20
main ( )
 {
        char string [ITEMS] [MAXCHAR], 
                dummy [MAXCHAR] ;
        int i = 0, j = 0 ;
      /* Reading the list   */
      printf (" Enter names of %d items \n ", ITEMS) ;
      while (i < ITEMS) 
           scanf ("%s", string [i++]) ;
     /*  Sorting begins  
     for (i =1; i < ITEMS; i++)   /* Outer loop begins */
     {
          for (j=1; j<= ITEMS - i; j++)  /* Inner loop begins  */ 
          {       
                if  (strcmp (string [j - 1], string [j] > 0)
                {  /*  Exchange of contents  */
                   strcpy (dummy, string [j - 1]) ;
                   strcpy (string [j - 1], string [j] ) ;
                   strcpy (string [j], dummy ) ;
               }
         }  /*  Inner loop ends  */ 
     }   /*   Outer loop ends  */
       /*  Sorting completd   */
       printf ("\nAlpphabetical list \n\n") ;
       for (i =0; i < ITEMS; i++)
          printf ("%s", string [i] ) ;
  }


Output:         Enter name of 5 items
                      London  Manchester Delhi Paris Moscow

                     Alphabetical list
                     Delhi
                     London
                     Manchester
                     Moscow
                     Paris 

Note that a two dimensional array is used to store the list of strings. Each string is read using a scanf function with %s format. Remember, if any string contains a while space, them the parts of the string after the white space will be treated as another item in the list by the scanf. In such cases, we should read the entire line as a string using a suitable algorithm. For example, we can use gets function to read a line of text containing a series of words. We may also use puts function in place of scanf for output. 
          
            

Illustration of string handling functions

Program 36) s1, s2, and s3 are three string variables. Write a program to read two string constants into s1 and s2 and compare whether they are equal or not. If they are not, join them together. Then copy the contents of s1 to the variable s3. At the end, the program should print the contents of all the three variables and their lengths.

In this program,during the first run, the input strings are "New" and "York". These strings are compared by the statement
                           x = strcmp (s1, s2) ;
Since they are equal, they are joined together and copied into s3 using statement 
                           strpy (s3, s1) ;
The program outputs all the three strings with their lengths. 
During the second run, the two strings s1 and s2 are equal, and therefore, they are not joined together. In this case all the three strings contain the same string constant "London"

                                PROGRAM

#include <string.h>
main ( ) 
 {
      char s1 [20], s2 [20], s3 [20] ;
      int x, 11, 12, 13 ;
      printf (" \n\nEnter two string constant \n") ;
      printf ("?") ;
      scanf ("%s %s", s1, s2) ;
    */  comparing s1 and s2  */
      x = strcmp (s1, s2) ;
      if (x  ! = 0)
      {
            printf (" \n\nStrings are not equal \n") ;
            strcat (s1, s2) ;   /* joining s1 and s2  */
      }
      else
           printf (" \n\nStrings are equal \n") ;
  /*   copying s1 to s3     */
     strcpy (s3, s1) ;
  /*  Finding length of strings   */
      l1  =  strln (s1) ;
      l2  =  strln (s2) ;
      l3  =  strln (s3) ;
 /* Output  */
     printf ("\ns1 = %s\t length = %d characters\n", s1, l1) ;
     printf ("s2 = %s\t length = %d characters\n", s2, l2) ;
     printf ("s3 = %s\t length = %d characters\n", s3, l3) ;
 }


Output:         Enter two string constants
                     ? New York


                     Strings are not equal
                     s1 = NewYork  length = 7 characters
                     s2 = York         length = 4 charcaters
                     s3 = NewYork  length = 7 characters


                     Enter two string constants
                     ?  London  London
       
                      Strings are equal
                     s1 = London length = 6 charcaters
                     s2 = London length = 6 characters
                     s3 = London length = 6 characters

Concatenation of string

Program 35) The names of employees in an organization are stored in three arrays, namely first_name, second_name, and last_name. Write a program to concatenate the three parts into one string to be called name.

In this program, three for loops are used to copy the three strings. In the first loop, the character contained in the first_name are copied into the variable name until the null character  is reached. The null character is not copied; instead it is replaced by a space by the assignment statement
                                     name [i] = ' ' ;
Similarly, the second _name is copied into name, starting from the column just after the space created by the above statement. This is achieved by the assignment statement
                           name [i + j + 1] = Second_name [j] ;
If first_name contains 4 characters then the value of i at this point will be 4 and therefore the first character from second_name will be placed in the fifth cell of name. Note that we have stored a space in the fourth cell.
In the same way, the statement                                                                      name [i + j + k + 2] = last_name [k] ;
is used to copy the characters from last_name into the proper location of name. In this example, it is important to note the use of the expressions i + j + 1 and i + j + k +2


                                   PROGRAM

main ( )
 {
       int i, j, k ;
       char first_name [10] = {"VISWANATH"} ;
       char second_name [10] = {"PRATAP"} ;
       char last_name [10] = {"SINGH"} ;
       char name [30] ;
     /*  Copy first_name into name  */
       for (i = 0; first_name [i] ! =  '\0' ; i++)
            name [i] = first name [i] ;
   
   /*   End first name with a space  */
         
      name [i] = ' ' ;
   
  /*  Copy second_name into name  */
         
      for (j = 0; second_name [j]  ! =  '\0'  ; i++)
              name [i + j + 1] = second_name [j] ;
  
  /*  End second_name with a space  */
         
      name [i + j +1] = ' ' ;
  
 /*   Copy last_name into name  */
        
     for (k = 0; last_name [k]  ! =  '\0' ; k++)
              name [i+ j + k + 2] = '\0' ;
              printf ("\n\n") ;
              printf ("%s \n", name) ;
 }

Output:      VISHWANATH  PRATAP  SINGH

Writing strings in using %s format

Program 34) Write a program to store the string "United Kingdom" in the array country and display the string under format specifications.

This program output illustrates the following features of the %s specifications.
1. When the field width is less than the length of the 
    string, the entire string is printed.
2. The integer value on the right side of the decimal 
    point specifies the numbers of characters to be 
    printed.
3. When the number of characters to be printed is 
    specified as zero, nothing is printed.
4. The minus sign in the specification causes the string
    to be printed left-justified.
5. The specification % .ns prints the first n characters of 
    the string.


                                     PROGRAM

main ( )
 {
       char country [15] = "United Kingdom" ;
       printf ("\n\n") ;
       printf ("*123456789012345*\n") ;
       printf (" --------- \n") ;
       printf ("%15s\n", country) ;
       printf ("%5s\n", country) ;
       printf ("%15.6s\n", country) ;
       printf ("%-15.6s\n", country) ;
       printf ("%15.0s\n", country) ;
       printf ("%.3s\n", country) ;
       printf("%s\n", country) ;
       printf ("---------- \n") ;
 }


Output:       *123456789012345
                   ---------
                   United Kingdom
                   United Kingdom
                              United
                   United


                   Uni
                   United Kingdom
                  ----------

Copying one string into another

Program 33) Write a program to copy one string into another and count the number of characters copied.

In this program, we use a for loop to copy the characters contained inside string2 into the string1. The loop is terminated when the null character is reached. Note that we are again assigning a null character to the string1.

                                    PROGRAM

main ( ) 
 {
       char string1 [80], string2 [80] ;
       int i ;
   
       printf ("Enter a string \n") ;
       printf ("?") ;


       scanf ("%s", string2) ;
       for (i = 0; string2 [i]  ! =  '\0'; i++) 
                  string1 [i] = string2 [i] ;
       string1 [i] = '\0' ;


       printf ("\n") ;
       printf ("%s\n", string1) ;
       printf ("Number of characters = %d\n", i) ;
 }


Output:      Enter a string
                  ?Manchester


                   Manchester
                   Number of characters = 10


                   Enter a string 
                   ?Westmminister

                   Westminister
                   Number of characters = 11


 

Program to read a line of text from terminal

Program 32) Write a program to read a line of text containing a series of words from the terminal.

This program can read a line of text (up to a maximum of 80 characters) into the string line using getchar function. Every time a character is read, it is assigned to its location in the string line and then tested for newline character. When the new line character is read (signalling the end of line), the reading loop is terminated and the new line character is replaced by the null character to indicate the end of character string. 
When the loop is exited, the value of the index is one number higher than the last character position in the string (since it has been incremented after assigning the new character to the string). Therefore the index value c-1 gives the position where the null character is to be stored.

                                       PROGRAM

#include <stdio.h>
main ( )
 {
       char line [81], character ;
       int c ;
       c = 0 ;
       printf ("Enter text. Press <Return> at end\n") ;
       do
       {
            character = getchar ( ) ;
            line [c] = character ;
            c++ ;
       }
       while (character ! = '\n') ;
       c = c - 1 ;
       line [c] = '\0' ;
       printf ("\n%s\n", line) ;
 }

Output:    Enter text. Press <Return> at end
                Programming in C is interesting.
                Programming in C is interesting.
                Enter text. Press <Return> at end
                National Centre for Expert Systems, Hyderabad.
                National Center for Expert Systems, Hyderabad.