Comparing Strings

Comparing numbers is a very easy task, involving the standard comparison operators (==, <, >, <=, >=), but you cannot compare strings using them. Instead, there is the strncmp() function:

strcmp (string1, string2);

This function returns the value 0 if the two strings are the same and returns a nonzero value otherwise. Normally you'll want to use this as a condition in an if-else statement:

if (strcmp(string1, string2) == 0) {
   // The same!
} else {
   // Different!
}

Our next example creates a tough but functioning guessing game, where the user must guess a three-letter word.

Adjusting for Case

The example is this section—guessing a random three-letter word—is hard enough without trying to adjust for the case of the word. The strcmp() function is case sensitive, meaning that Cat, cat, and CAT do not match each other.

The easiest way to correct for this is to use the strcasecmp() function, which is a case-insensitive version of strcmp().

Another alternative is to convert both strings being compared to either upper or lower case. So Cat, cat, and CAT would all be turned into cat or CAT, depending upon your preference. You can do that by running every character in a string through either the toupper() or tolower() function, defined in the ctype.h file.


To compare two strings

1.
Create a new file or project in your text editor or IDE.

2.
Type the standard beginning lines of code (Script 11.4):

/* guess.c - Script 11.4 */
#include <stdio.h>

Script 11.4. This guessing game reads in a word and compares it to the right answer. The process continues until the user guesses the correct word.


3.
Include the string.h header:

#include <string.h>

Since this application makes use of the strcasecmp() function, you must include the string.h file where it is defined.

4.
Add a function prototype:

void discard_input (void);

Because this application relies so heavily on precise user input, it will utilize the discard_input() function, first defined in Chapter 7, “Creating Your Own Functions.” This prototype indicates that the function takes no arguments and returns no values.

5.
Begin the main function:

int main (void) {

6.
Define two character arrays:

char guess[10];
const char answer[] = "coy";

The first array will store the user's guess. The second array is a constant that stores the right answer, which is initialized here as well.

If you wanted, you could make the game less exact by limiting the size of guess[] to four characters. That way, only the first three characters entered (plus the ) would be assigned to guess. The end result would be that the user-submitted word doggerel would still match the answer dog.

7.
Prompt for and read in the user's first guess:

printf("Guess what three-letter word
 I'm thinking of: ");
scanf("%9s", guess);

All of this is familiar territory, where the user is prompted and that entered text is assigned to the guess variable.

8.
Discard any extraneous input:

discard_input();

Calling this function here will discard any other characters typed after the application has read in the nine (or up to nine) characters assigned to guess. By using this, we ensure that any extraneous characters will be discarded instead of being read in as part of the next guess.

9.
Begin a while loop to compare the user's answer against the right word:

while (strcasecmp(answer, guess)) {

The while loop evaluates a condition and, if true, executes the code therein. With this specific loop, the condition is a call to the strcasecmp() function, comparing the value of answer to the value of guess. If the two strings do not have the same value, the function will return a nonzero value, which is true in C. In such cases, the contents of the loop (Step 10), which says the guess was wrong and that the user should try again, are executed.

If the submitted guess matches the right answer, the strcasecmp() function will return 0, which is false in C, and the loop will not be entered.

10.
Complete the while loop, re-prompting the user, reading in the answer, and discarding any extraneous input:

      printf("Incorrect! Guess again:
 ");
      scanf("%9s", guess);
      discard_input();
}

The contents of the while loop will only be executed if the strcasecmp() function determines that guess and answer are different. If so, the user is re-prompted, the next guess is read in, and the remaining input is discarded. After these three lines of code have been executed, the loop's condition will be reevaluated—testing the new guess against the right answer. The process will continue until the user guesses the correct answer.

11.
Tell the user they got it right:

printf("You are correct!");

The application will only reach this point in the code—after the while loop—if the user enters the correct answer.

12.
Complete the main function:

   getchar();
   return 0;
}

13.
Define the discard_input() function:

void discard_input (void) {
    char junk;
    do {
            junk = getchar();
    } while (junk!= '
'),
}

This function must be defined in order to use it. Revisit Chapter 7 for the description of this particular syntax.

14.
Save the file as guess.c, compile, and debug as necessary.

15.
Play the game (Figures 11.10 and 11.11).

Figure 11.10. The application continues to run until the user enters the right answer.


Figure 11.11. If the answer is guessed on the first try, the while loop is never entered (see Script 11.4).


✓ Tips

  • If you're curious, strcmp() returns a negative number if string1 comes before string2 alphabetically and returns a positive number if string2 comes before string1.

  • The strncmp() function compares two strings character by character until a difference is found or until n number of characters have been compared:

    char s1[] = "catastrophic";
    char s2[] = "catalog";
    strcmp(s1, s2); // positive number
    strncmp(s1, s2, 4); // 0
    
  • If you're only comparing single characters, use the standard equality operator:

    if ('A' == 'B') { ...
    

Searching Through Strings

If what you'd like to do is find a particular character within a string, rather than compare one string to another, there are a few C functions you can use.

The strchr() function searches a string for a character, returning the address of that character in the string, or NULL if it was not found:

char string[] = "That was quick.";
char *address = NULL;
address = strchr(string, 'q'),
printf ("At %p you'll find %c.", address, *address);

Conversely, strrchr() finds the last occurrence of a character in a string, returning that address if it was found.

char string[] = "That was quick.";
char *address = NULL;
address = strrchr(string, 'a'),
printf ("At %p you'll find %c.", address, *address);

The strpbrk() function takes this concept one step further by searching a string for the first occurrence of any of a list of characters:

char string[] = "That was quick.";
char *address = NULL;
address = strpbrk(string, "aeiou");
printf ("At %p you'll find %c.",
 address, *address);

Finally, strstr() finds the first location of string2 within string1:

char haystack[] = "Is there a needle in here?";
char *address = NULL;
address = strstr(haystack, "needle");
printf ("%s was found beginning at %p. ", "needle", *address);

Obviously, in each of these examples, you'd want to check that address contained a non-null value (meaning that the search succeeded) before reporting on the results.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset