211: Programming For IS 1 --- Lecture Nov. 17

Topics:

Array of Character Strings
Inputting an Array of Character Strings
Copying Character Strings
Comparing two Character Strings
Insertion Sort for a List of Character Strings

Array of Character Strings

Example: Define an array Names of size MAX of character strings of size LENGTH, where MAX and LENGTH are constant integer objects.

char Names[MAX][LENGTH]

Inputting an Array of Character Strings

The following function inputs character strings into the array Strings until a null string is encountered.

void GetData(char Names[MAX][LENGTH],int &Size)
{
   Size = 0;
   cout << "Enter student's name (or period to terminate): ";
   cin >> Name[0];
   while (Name[Size][0] != '.')
   {
      ++Size;
      if(Size > MAX)
	 break;
      cout << "\nEnter student's name (or period to terminate): ";
      cin >> Names[Size];
    } //END WHILE
} //END GetData()
Copying Character Strings

The following statement may not work:

String1 = String2;

To copy String2 into String1 you will need to use:

strcpy(String1,String2)

You need to include the header file string.h.

Comparing Two Character Strings

The following Boolean expression may not be valid:

String1 < String2

You will need to use the function call

strcmp(String1,String2)

which has a negative value, zero value or positive value depending on whether String1 is less than, equal of greater than String2, respectively.

Again you need to include the header file string.h to use this function.

Insertion Sort for a List of Character Strings

The following program sorts an array of names using Insertion Sort. This version of Insertion Sort utilizes the string operations discussed above.

Insertion Sort for Sorting Strings