Activity 11-1 - Introduction to Strings
                        C-string Functions



In the previous lab, you learned to create arrays of different sizes to handle some numerical calculations.  In this lab, you will use arrays of characters which will be referred to as strings.  We can create a string in two different ways, 1) using the C-string style, and 2) using the string class.

To create an array using a C-string, we first need to declare an array of characters to store the characters that make the string (word).  You have to keep in mind that when you use the C-string style to create a string, you are required to have an extra space at the end for character '\0' which is known as the null character.  The null character, '\0', marks the end of the string.  In general, a string in which the null character marks its end is referred to as a C-string.  The following array is an example of a C-string, which allows us to store 7 or fewer characters:

char mystring[8];

Note this array can hold 8 characters, but the last one is kept for '\0'.  If we initialize this array with "Hello":

char mystring[8] = "Hello";     Or by using:          char mystring[] = "Hello";

Then we will have:
 
Imaginary
Memory
Address
1023
1024
1025
1026
1027
1028
1029
1030
Array Index
0
1
2
3
4
5
6
7
Indexed
numlist Variable
mystring[0]
mystring[1]
mystring[2]
mystring[3]
mystring[4]
mystring[5]
mystring[6]
mystring[7]
Array
Content
H
e
l
l
o
\0
?
?

Note that we haven't used the last two elements and we do not know the content of those locations are.

Important Note:
Please remember that the above two statements used to initialize the array are equivalent, but the following IS NOT equivalent to these two:
 char mystring[] = {'H', 'e', 'l', 'l', 'o'};

The above two initializations put a '\0, after the 'o', but this one doesn't put the '\0' at any place in the array.

Comparing two strings
When we dealt with numbers, it was easy to compare two numbers to see whether they are the same using ==.  However, when we deal with C-strings, we cannot use this method.  For example, if we want to check whether mystring is the same as yourstring, we cannot use the following:

char mystring[] = "Hello";
char yourstring[] = "hello";

if(mystring == yourstring)      WRONG

In order to do this, we will use a function strcmp.

if( strcmp(mystring, yourstring) == 0)

The strcmp function will return 0 if the strings are the same.  The strcmp function uses the ordering relationship known as lexicographic order to determine whether these two are the same.

Important Note:
In order to use the strcmp function, you need to use the #include<cstring> in your programs.  The following table shows a list of some of the functions in that header file.
 
 

Function Name
Description
Cautions
strcpy
use: strcpy(Target_String, Source_String)
Copies the C-string variable Source_String into the C-string variable Target_String Does not check to see if the Target_String is large enough to hold the Source_String
strncpy
use: strncpy(Target_String, Source_String, Limit)
The same as strcpy except that at most Limit characters are copied. Not implemented in all versions of C++
strcat
use: strcat(Target_String, Source_String)
Concatenates (put together) the C-string variable Source_String onto the end of the C-string variable Target_String Does not check to see if the Target_String is large enough to hold both strings together
strncat
use: strncat(Target_String, Source_String, Limit)
The same as strcat except that at most Limit characters are appended Not implemented in all versions of C++
strlen
int length;
use: length = strlen(Source_String)
Returns an integer equal to the length of the Source_String, excluding the '\0' character. 
strcmp
use: strcmp(String_1, String_2)
  • Returns 0 if String_1 and String_2 are the same. 
  • Returns a value < 0 if String_1 is less than String_2 
  • Returns a value > 0 if String_1 is greater than String_2
Thus, it returns a non-zero value when the two C-strings are not the same.
When the two C-strings are the same it returns 0, which converts to false.  That may cause confusion as you may expect to get 1 when the two C-stringsa are the same. 
strncmp
use: strncmp(String_1, String_2, Limit)
The same as strcmp except that at most Limit characters are compared Not implemented in all versions of C++
getline
use:
cin.getline(String_variable, Max_characters+1)
or 
ifstream  s;  // an input stream
s.getline(String_variable, Max_characters+1)
Reads a line of input up to Max_characters length and places the C-string of characters on that line into a C-string variable String_variable If the line is longer than the maximum length defined, it only copies the first Max_characters-1 characters on that line

Follwing is an example program in which we use some of these functions.

// P11_1.cpp - This program demonstrates the use of C-string functions

#include<iostream>
#include<cstring>
using namespace std;

int main( )
{
     char s1[8], s2[8];
     int length1, length2;
     int count = 0;

  // Initialize the two strings
     strcpy(s1,"Black");
     strcpy(s2,"Black");

  while(count < 2)
  {
      if(count > 0)
      // After the first time ask the user to enter them
      {
          cout << "Now I let you enter two strings \n";
          cout << "Enter the first string, then the second \n";
          // Another way to initialize the two strings
          cin >> s1 >> s2;
      }
      // Find their lengths
      length1 = strlen(s1);
      length2 = strlen(s2);

      // Compare their length
      if(length1 == length2)
     {
              cout << "The two strings are the same length, are they the same? \n";
      }

      // See if they are the same
      if(! strcmp(s1, s2) )
      {
           cout << "The two strings: ";
           cout << s1 << " and " << s2 << " are the same \n";
      }
      else
      {

          cout << "The two strings: ";
          cout << s1 << " and " << s2 << " are NOT the same \n";
      }
      count++;
   }

   return 0;
}

C-String Input and Output
Note the way we initialized the strings from the keyboard:
          cin >> s1 >> s2;
and we display their values using:
          cout << s1 << " and " << s2 << " are NOT the same \n";

When we did the reading, a blank space between the two strings that we type will tell the compiler which word goes to which string. Thus, if we would enter:
"Black  board", s1 would take "Black" and s2 would take "board".  The same thing would happen if we would have entered these two as:
Black
board

C-String-to-Number Functions
The functions atoi, atol, and atof can be used to convert a C-string of digits to the corresponding numeric value.  The first two functions convert the C-string to integers of type int or long, respectively.  The last one will convert the C-string to double.
Example:
int x = atoi("675");

This sets the value of x to 675.

In order to use these functions, you need to have #include<cstdlib> in your program.

Exercise 11.1
Modify the P11_1.cpp program to ask users for two strings then:
    1) Append the second string to the end of the first string and display the resulting string,

    2) Display a message on whether or not the word is a Palindrome.  Such strings are the same when you write them backward.
    For example:  race + car = racecar  .... this word written backwards is also racecar, thus, it is a palindrome.

Call your new program ex11_1.cpp.