Sunday, December 27, 2009

7.5 ARRAYS AND STRINGS

Most C compilers include library functions that allow strings to be compared, copied or concatenated (i.e combined, one behind another).Other library functions permit operations on individual characters within strings; e.g., they allow individual characters to be located within strings, and so on.The following example illustrates the use of some of these library functions.

/* sort a list of strings alphabetically using a two-dimensional character array*/


#include < stdio.h >
#include < stdlib.h >
#include < string.h >


void reorder (int n, char x[][12]);  /* function prototype*/


main()
{
int i, n = 0;
char x[10][12];


printf ("Enter each string on a separate line below\n\n");
printf ("Type \ 'END\ ' when finished\n\n");


/*read in the list of strings*/
do  {
printf ("string %d: ", n+1);
scanf ("%s", x[n]);

} while (strcmp(x[n++], "END"));


/* adjust the value of n*/
n--;


/* reorder the list of strings*/
reorder(n, x);


/* display the reordered list of strings */
printf("\n\nReordered List of strings: \n");
for (i=0; i < n;++i)
printf("\nstring %d: %s", i+1, x[i]);
}


void reorder(int n, char x[][12])  /* rearrange the list of strings */
{
char temp[12];
int i, item ;




for (item=0; item <  n-1;++item)


/* find the lowest of all remaining strings */
for (i=item+1; i <  n;++i)


if (strcmp(x[item], x[i]) > 0)  {
/* interchange the two strings */
strcpy(temp, x[item]);
strcpy(x[item], x[i]);
strcpy(x[i], temp);


}
return;
}

The strcmp function appears in two different places within this program : in main, when testing for a stopping condition, and in rearrange, when testing for the need to interchange two strings.The actual string interchange is carried out using strcpy.The dialog resulting from a typical execution of the program is shown below.The user's response are underlined, as usual.

Enter each string on a separate line below

Type 'END ' when finished

string 1: PACIFIC
string 2: ATLANTIC
string 3: INDIAN
string 4: CARIBBEAN
string 5: BERING
string 6: BLACK
string 7: RED
string 8: NORTH
string 9: BALTIC
string 10: CASPIAN
string 11: END

Reordered List of strings:


string 1: ATLANTIC
string 2: BALTIC
string 3: BERING
string 4: BLACK
string 5: CARIBBEAN
string 6: CASPIAN
string 7: INDIAN
string 8: NORTH

string 9: PACIFIC
string 10: RED

No comments:

Post a Comment